Thanks numerix.
I’ve now tested my program against 20000 test cases, including the min size, max size, and many other big numbers, and compared the output with both spojtoolkit and some solution I found on the web - all give the same answers.
I can only think there must be some corner case I’ve not considered.