Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save deepaksinghvi/8df0b50d2a7099716322e2503c85678e to your computer and use it in GitHub Desktop.
Save deepaksinghvi/8df0b50d2a7099716322e2503c85678e to your computer and use it in GitHub Desktop.
public class MaximumSumOfHourGlassInMatrix {
private static int[][] input1 = {
{1, 2, 3, 4, 5},
{0, 5, 1, 5, 2},
{0, 0, 0, 1, 3},
{4, 1, 1, 0, 1},
{0, 0, 0, 0, 3},
};
private static int[][] input2 = {
{3, 0, 0, 5},
{2, 5, 5, 5},
{0, 0, 0, 1},
{4, 4, 0, 0},
{0, 0, 3, 0},
};
private static int[][] input3 = {
{-1, -1, 0, -9, -2, -2},
{-2, -1, -6, -8, -2, -5},
{-1, -1, -1, -2, -3, -4},
{-1, -9, -2, -4, -4, -5},
{-7, -3, -3, -2, -9, -9},
{-1, -3, -1, -2, -4, -5}
};
public static void main(String args[]) {
System.out.println("Max Sum for input1 is: " + findMaxSum(input1) + "\n");
System.out.println("Max Sum for input2 is: " + findMaxSum(input2)+ "\n");
System.out.println("Max Sum for input3 is: " + findMaxSum(input3)+ "\n");
}
private static int findMaxSum(int arr[][]) {
int rowLength = arr.length;
if (rowLength < 3) {
System.err.println("Bad Input, row length must be 3 or more");
return -1;
}
int colLength = arr[0].length;
if (colLength < 3) {
System.err.println("Bad Input, column length must be 3 or more");
return -1;
}
int maxSum = Integer.MIN_VALUE;
int tempMaxSum = Integer.MIN_VALUE;
StringBuilder maxSumStr = new StringBuilder();
String resultMaxSumStr = "";
for (int i = 0; i < rowLength - 2; i++) {
for (int j = 0; j < colLength - 2; 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];
maxSum = Math.max(maxSum, sum);
if (tempMaxSum < maxSum) {
maxSumStr.append(arr[i][j]).append(" ").append(arr[i][j + 1]).append(" ")
.append(arr[i][j + 2]).append("\n")
.append(" ").append(arr[i + 1][j + 1]).append("\n")
.append(arr[i + 2][j]).append(" ").append(arr[i + 2][j + 1]).append(" ")
.append(arr[i + 2][j + 2]).append("\n\n");
tempMaxSum = maxSum;
resultMaxSumStr = maxSumStr.toString();
maxSumStr = new StringBuilder();
}
}
}
System.out.print(resultMaxSumStr);
return maxSum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment