'Finding the minimum sum and maximum sum of a list of integers in an array

I am currently working on a HackerRank practice question and I only pass 5 test cases and I have no idea why. I've thought of all edge cases that I can think of myself but I fail most test cases.

Problem: Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example - The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints

16 24

This is my solution so far:

public static void miniMaxSum(List<Integer> arr) {
    // Write your code here
        Collections.sort(arr);
        int max = 0;
        int min = 0;
        int sum = 0;
        int smallest = arr.get(0);
        int largest = arr.get(4);
        for (int i=0; i<arr.size(); i++) {
            sum += arr.get(i);
        }
        min = sum - largest;
        max = sum - smallest;
   
        
        System.out.print(min+ " " + max);

    }

I have no idea what test cases I'm failing since it doesn't tell me. I've tried arrays with duplicates, massive numbers, unsorted, and it all gives me expected answer. Please help!



Solution 1:[1]

Use long datatype because there is possibility of Integer overflowing or use 16 bit Integer.

public static void miniMaxSum(List<Integer> arr) {
// Write your code here
    Collections.sort(arr);
    long max = 0;
    long min = 0;
    long sum = 0;
    long smallest = arr.get(0);
    long largest = arr.get(4);
    for (int i=0; i<arr.size(); i++) {
        sum += arr.get(i);
    }
    min = sum - largest;
    max = sum - smallest;

    
    System.out.print(min+ " " + max);

}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vinzee