Given a 6 x 6 2D Array, arr:
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation:
a b c
d
e f g
There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print the maximum hourglass sum. The array will always be 6 x 6.
Example
arr
-9 -9 -9 1 1 1
0 -9 0 4 3 2
-9 -9 -9 1 2 3
0 0 8 6 6 0
0 0 0 -2 0 0
0 0 1 2 4 0
The 16 hourglass sums are:
-63, -34, -9, 12,
-10, 0, 28, 23,
-27, -11, -2, 10,
9, 17, 25, 18
The highest hourglass sum is 28 from the hourglass beginning at row 1, column 2:
0 4 3
1
8 6 6
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Function Description
Complete the function hourglassSum in the editor below.
hourglassSum has the following parameter(s):
Returns
Input Format
Each of the 6 lines of inputs arr[i] contains 6 space-separated integers arr[i][j].
Output Format
Print the largest (maximum) hourglass sum found in arr.
어렵게 생각했지만, 단순하게 처음부터 모래시계 모양대로 쭉 0부터 3번쨰 인덱스까지 sum을 계산해서 최대값을 갱신해주면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
static int[][] arr = new int[6][6];
private static int hourglassSum (int[][] arr) {
int large = -64;
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];
large = Math.max(sum, large);
}
}
return large;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 6; i++) {
String[] numArr = br.readLine().split(" ");
arr[i] = Arrays.stream(numArr).mapToInt(Integer::parseInt).toArray();
}
System.out.println(hourglassSum(arr));
}
}