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?
CodePudding user response:
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);
}