Search code examples
javaarraysindexingstdinindexoutofboundsexception

MiniMaxSum passes first test case, fails with large values (hackerrank)


I'm doing a challenge on hackerrank that finds the maximum and minimum sub-sum of an array of 5 values. I got it to pass the first test case (see below), but it appears to run into an ArrayIndexOutOfBounds Exception on larger values.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

// Complete the miniMaxSum function below.
static void miniMaxSum(int[] arr, int n) {
    int max=-10000;
    int min=10000;
    int indexMax=-10000;
    int indexMin=10000;
    int sum=0;

    //Find sum of all values in array
    for (int i : arr)
    {
        sum += i;
    }

    //Find value of Max and index of Max
    for (int i : arr)
    {
        if (i >= max)
        {
            max=arr[i-1];
            indexMax=i-1;
        } 
    }

    //Find value of Min and index of Min
    for (int i : arr)
    {
        if (i <= min)
        {
            min=arr[i-1];
            indexMin=i-1;
        }
    }

    //Remove max value from minimum sub sum value
    int minSubSum=sum-max;

    //Remove min value from maximum sub sum value
    int maxSubSum=sum-min;

    System.out.println(minSubSum +  " " + maxSubSum);

}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int[] arr = new int[5];

    String[] arrItems = scanner.nextLine().split(" ");
    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

    for (int i = 0; i < 5; i++) {
        int arrItem = Integer.parseInt(arrItems[i]);
        arr[i] = arrItem;
    }
    int n = arr.length;
    miniMaxSum(arr,n);

    scanner.close();
}
}

Failed Test case

Input (stdin): 7 69 2 221 8974 Expected Output: 299 9271

Compiler Message Runtime Error Error (stderr) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at Solution.miniMaxSum(Solution.java:28) at Solution.main(Solution.java:72)

Passed Test Case

Input (stdin): 1 2 3 4 5 Your Output (stdout): 10 14 Expected Output: 10 14

Any idea for this error? Any solution that will fit into my approach?

Thanks!


Solution

  • The problem lays in this piece of code

    //Find value of Max and index of Max
        for (int i : arr)
        {
            if (i >= max)
            {
                max=arr[i-1];
                indexMax=i-1;
            } 
        }
    

    Specifically, max=arr[i-1] is the culprit. You are already looping through the integers in the array with the for-loop.

    In your second example, the first number is 7. 7 is larger as the current max, but the array is only 5 long. arr[i-1] will translate to arr[7-1] = arr[6], which is out of bounds for the array.

    The max will have to be stored with

    max = i instead of max=arr[i-1]

    as i already holds the value of the integer, not the index.

    The same edit will have to be applied to the min function.