Java 2D Array Solution
Problem Overview
Original Problem: Java 2D Array | HackerRank
Difficulty: Easy
Category: 2D Arrays
Description: We are given a 6×6 two-dimensional array of integers. Our task is to identify all hourglass patterns within this array, calculate the sum of each, and determine the maximum hourglass sum.
Understanding the Problem
TWe're asked to find the hourglass in a 6×6 array that has the largest total sum. An hourglass is a specific shape of 7 elements within a 3×3 subset of the array, arranged as follows:
1 2 3
4
5 6 7
Input:
Six lines of input, where each line contains 6 space-separated integers.
Each integer is between -9 and 9, inclusive.
Output:
A single integer: the maximum hourglass sum found in the 2D array.
Initial Reasoning
The template code already reads the 6x6 input and stores it in a 2D list. From there, we need to:
Loop over all possible hourglass positions (top-left of each 3×3 grid)
Compute the sum of the 7 values forming each hourglass
Keep track of the largest sum encountered
To do this effectively, we start with a variable holding the lowest possible hourglass sum. Then, we iterate through the grid, calculate each hourglass sum, and update our tracking variable when a higher sum is found.
Pseudocode
// Main function:
Read the lines of input and store in a 2D array
Initialise a variable to track the maximum
For each row that can be the top of an hourglass
For each column that can be the leftmost side of an hourglass
Calculate the hourglass sum
If the sum is greater than the current maximum
Update the maximum
Print the maximum
Solution Code
// Note this is one of many possible solutions
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
List> arr = new ArrayList<>();
// Reading 6x6 array from input and storing in a 2D array
IntStream.range(0, 6).forEach(i -> {
try {
arr.add(
Stream.of(bufferedReader.readLine().trim().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
bufferedReader.close();
int maxSum = -9 * 7; // Initialize to lowest possible value
// Iterate through all possible hourglass starting points
for (int i = 0; i < 4; i++) { // rows
for (int j = 0; j < 4; j++) { // columns
int 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);
// Update maxSum if current sum is greater
if (sum > maxSum) {
maxSum = sum;
}
}
}
System.out.println(maxSum);
}
}