0

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!

3
  • 1
    Well, they're not long integers, at the very least. Commented Sep 21, 2021 at 0:10
  • that...solved it. i feel so dumb but thank you so much Commented Sep 21, 2021 at 0:12
  • Glad you worked it out :) Commented Sep 21, 2021 at 0:17

1 Answer 1

0

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);

}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.