HackerRank最小最大和问题输出转long类型异常排查求助
Hey there, let's break down why you're seeing negative numbers in some test cases and how to fix it.
The Root Cause
Your current code has a classic integer overflow issue. Here's what's happening:
When you do arr[1] + arr[2] + arr[3] + arr[4], all those values are int types. Even though you're assigning the result to a long variable, the addition happens as int operations first. If the sum of four ints exceeds the maximum value an int can hold (which is 2^31 - 1 or 2147483647), the sum overflows and wraps around to a negative number. By the time it gets stored in your long array, the damage is already done.
Fixing Your Existing Code
The simple fix is to cast at least one element in each sum to long before adding. This forces the entire addition operation to use long arithmetic, preventing overflow. Here's how to adjust your code:
import java.util.Arrays; static void miniMaxSum(int[] arr) { int n = arr.length; long[] ar = new long[n]; // Cast one element to long in each sum to trigger long arithmetic ar[0] = (long)arr[1] + arr[2] + arr[3] + arr[4]; ar[1] = (long)arr[0] + arr[2] + arr[3] + arr[4]; ar[2] = (long)arr[0] + arr[1] + arr[3] + arr[4]; ar[3] = (long)arr[0] + arr[1] + arr[2] + arr[4]; ar[4] = (long)arr[0] + arr[1] + arr[2] + arr[3]; Arrays.sort(ar); // No need to create a separate array, sort the original long array long min = ar[0]; long max = ar[4]; System.out.print(min + " " + max); }
A More Efficient Approach
Instead of calculating all four sums explicitly, you can compute the total sum of all five elements first. Then:
- The minimum sum is total sum minus the largest element in the array
- The maximum sum is total sum minus the smallest element in the array
This approach uses fewer calculations and avoids redundant code:
static void miniMaxSum(int[] arr) { long totalSum = 0; long minVal = Integer.MAX_VALUE; long maxVal = Integer.MIN_VALUE; for (int num : arr) { totalSum += num; // Adding int to long automatically promotes to long if (num < minVal) { minVal = num; } if (num > maxVal) { maxVal = num; } } long minSum = totalSum - maxVal; long maxSum = totalSum - minVal; System.out.println(minSum + " " + maxSum); }
Why This Works
- By iterating through the array once, we compute the total sum (as a
long, so no overflow), track the smallest and largest elements. - Subtracting the largest element from the total gives us the sum of the four smallest elements (minimum sum).
- Subtracting the smallest element gives us the sum of the four largest elements (maximum sum).
This method is not only more efficient (O(n) time instead of O(n log n) from sorting) but also cleaner and less error-prone.
内容的提问来源于stack exchange,提问作者Anurag

