Java - How to Solve this 2D Array Hour Glass?
Remove the if (arr[arr_i][arr_j] > 0)
statement. It prevents finding the answer at row 1, column 0, because that cell is 0
.
Comments for other improvements to your code:
What if the best hourglass sum is
-4
? You should initializetmp_sum
toInteger.MIN_VALUE
. And name itmaxSum
, to better describe it's purpose.You shouldn't define
sum
outside the loop. Declare it when it is first assigned, then you don't have to reset it to0
afterwards.Your iterators should be just
i
andj
. Those are standard names for integer iterators, and keeps code ... cleaner.
If you prefer longer names, userow
andcol
, since that is what they represent.You don't need parenthesis around the array lookups.
For clarity, I formatted the code below to show the hourglass shape in the array lookups.
Scanner in = new Scanner(System.in);
int arr[][] = new int[6][6];
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
arr[i][j] = in.nextInt();
}
}
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
int sum = arr[i ][j] + arr[i ][j + 1] + arr[i ][j + 2]
+ arr[i + 1][j + 1]
+ arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
if (maxSum < sum) {
maxSum = sum;
}
}
}
System.out.println(maxSum);