Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting an error for this hour glass problem with Java?

I am supposed to return the max hourglass sum. I am looping through the 2D array list to get the answer however I am getting 14 instead of 19 which is the correct answer. The code is given below:

public static int hourglassSum(List<List<Integer>> arr) {
    // Write your code here
    
    int hour_glass_sum = 0;
    
    int max = Integer.MIN_VALUE;
    
    for(int i=0; i < 4; i++) {
        //It loops through the entire list
        
        for(int j =0; j < 4; j++) {
            hour_glass_sum  = arr.get(i).get(j) + arr.get(i).get(j+1) + arr.get(i).get(j+2)+arr.get(i+1).get(j+1)+arr.get(i+2).get(j)+arr.get(i+2).get(j+1)+arr.get(i+2).get(j+2); 
        } 
        
        max = Math.max(max, hour_glass_sum);
    }
    
    return max;

    }

}


1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Expected Output: 19
My Output: 14

Can anyone tell me where am I making the error kindly?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You apply Math.max to the last index of j only

Change:

    for(int j =0; j < 4; j++) {
        hour_glass_sum  = arr.get(i).get(j) + arr.get(i).get(j+1) + arr.get(i).get(j+2)+arr.get(i+1).get(j+1)+arr.get(i+2).get(j)+arr.get(i+2).get(j+1)+arr.get(i+2).get(j+2); 
    } 
        
    max = Math.max(max, hour_glass_sum);

to :

    for(int j =0; j < 4; j++) {
        hour_glass_sum  = arr.get(i).get(j) + arr.get(i).get(j+1) + arr.get(i).get(j+2)+arr.get(i+1).get(j+1)+arr.get(i+2).get(j)+arr.get(i+2).get(j+1)+arr.get(i+2).get(j+2); 
        max = Math.max(max, hour_glass_sum);
    } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading