Search code examples
java

HackerRank Task "Mini Max Sum" solution not passing 3 of the 13 test cases, can someone tell me what i'm doing wrong


This is for the "Mini Max Sum" problem on HackerRank, I can't see why it doesn't have a check mark on all of the test cases. Can someone tell me where my problem lies at. The question is:

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.)

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        long[] arr = new long[5];
        long total = 0, max = 0, min = 0;
        for(int arr_i=0; arr_i < 5; arr_i++){
            arr[arr_i] = in.nextLong();
            min = arr[0];
            total += arr[arr_i];
            if (arr[arr_i] > max)
                max = arr[arr_i];
            if (arr[arr_i] <= min)
                min = arr[arr_i];
        }
        System.out.println((total - max) + " " + (total - min));
    }
}

Solution

  • The problem are the initial values of both min and max.

    1. min is being reset to the first values inside the loop, so it will probably only work if the first or the last value is the minimum one;

    2. max starts with zero, so if all values are negative, max will stay at zero (instead of one of the input values).

    Hints: set min and max on the first iteration (i == 0) or, as suggested, use Integer.MAX_VALUE and Integer.MIN_VALUE respectively as initial value (actually long is not needed for min and max, neither is the array)