-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaxSumOfHourGlass.java
48 lines (37 loc) · 1.46 KB
/
MaxSumOfHourGlass.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.*;
class MaxSumOfHourGlass{ //2D Array
static int findMaxSum(int[][] arr, int row, int col){
int maxSum = Integer.MIN_VALUE;
if(row<3 || col<3){
System.out.println("Max Sum cannot be found as the size of the array is less than 3");
return Integer.MIN_VALUE;
}
for(int i = 0; i<row-2; i++){
for(int j = 0; j<col-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);
}
}
return maxSum;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the no.of rows: ");
int row = input.nextInt();
System.out.println("Enter the no.of cols: ");
int col = input.nextInt();
int[][] arr = new int[row][col];
for(int i = 0; i<row; i++){
for(int j = 0; j<col; j++){
System.out.println("Enter the element at position: [" + i + "][" + j + "]");
arr[i][j] = input.nextInt();
}
}
int result = findMaxSum(arr, row, col);
if (result != Integer.MIN_VALUE) {
System.out.println("The maximum hourglass sum is: " + result);
}
input.close();
}
}