I need to find the minimum and maximum values that can be calculated by summing exactly (size - 1) elements in the arrays
Example:
arr = [1,2,3,4,5] minSum = 1+2+3+4 = 10 , maxSum = 2+3+4+5 = 14
Initially, I wrote the following code
public static void miniMaxSum(List<Integer> arr) {
List<Integer> sorted = arr.stream().sorted().collect(Collectors.toList());
Integer totalSum = sorted.stream().mapToInt(Integer::intValue).sum();
Integer minSum = totalSum - sorted.get(sorted.size()-1);
Integer maxSum = totalSum - sorted.get(0);
System.out.println(minSum + " "+maxSum);
}
For the simple test cases, it is working as expected, but then for the numbers with higher value it is overflowing and resulting in negative values, so I used BigInteger.
public static void miniMaxSum(List<Integer> arr) {
List<Integer> sorted = arr.stream().sorted().collect(Collectors.toList());
BigInteger totalSum = BigInteger.valueOf(sorted.stream().mapToInt(Integer::intValue).sum());
BigInteger minSum = totalSum.subtract(BigInteger.valueOf(sorted.get(sorted.size()-1)));
BigInteger maxSum = totalSum.subtract(BigInteger.valueOf(sorted.get(0)));
System.out.println(minSum + " "+maxSum);
}
Even then, it is resulting in negative values
Input : 793810624 895642170 685903712 623789054 468592370
Output : -1722871536 -1295821736
Why is it resulting in negative values even after using BigInteger, and how should it be handled?
The problem is that when you create
totalSum, the overflow already happened as you summed the integers asint, which means the result is also anint. Only then does your code convert this overflowed result to aBigInteger.Instead you need to do the calculation using
BigInteger:Which is equivalent to doing: