Maximum sum of hour glass in matrix

Given a 2D matrix, the task is that we find maximum sum of a hour glass.

```An hour glass is made of 7 cells
in following form.
A B C
D
E F G
```

Examples:

```Input : 1 1 1 0 0
0 1 0 0 0
1 1 1 0 0
0 0 0 0 0
0 0 0 0 0
Output : 7
Below is the hour glass with
maximum sum:
1 1 1
1
1 1 1

Input : 0 3 0 0 0
0 1 0 0 0
1 1 1 0 0
0 0 2 4 4
0 0 0 2 4
Output : 11
Below is the hour glass wuth
maximum sum
1 0 0
4
0 2 4
```

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

It is evident from definition of hour glass that number of rows and number of columns must be greater than 3. If we count total number of hour glasses in a matrix, we can say that the count is equal to count of possible top left cells in hour glass. Number of top-left cells in a hour glass is equal to (R-2)*(C-2). Therefore, in a matrix total number of hour glass is (R-2)*(C-2)

```mat[][] = 2 3 0 0 0
0 1 0 0 0
1 1 1 0 0
0 0 2 4 4
0 0 0 2 0
Possible hour glass are :
2 3 0  3 0 0   0 0 0
1      0       0
1 1 1  1 1 0   1 0 0

0 1 0  1 0 0  0 0 0
1      1      0
0 0 2  0 2 4  2 4 4

1 1 1  1 1 0  1 0 0
0      2      4
0 0 0  0 0 2  0 2 0
```

We consider all top left cells of hour glasses one by one. For every cell, we compute sum of hour glass formed by it. Finally we return maximum sum.

Below is C++ implementation of above idea.

```// C++ program to find maximum sum of hour
// glass in matrix
#include<bits/stdc++.h>
using namespace std;
const int R = 5;
const int C = 5;

// Returns maximum sum of hour glass in ar[][]
int findMaxSum(int mat[R][C])
{
if (R<3 || C<3)
return -1;

// Here loop runs (R-2)*(C-2) times considering
// different top left cells of hour glasses.
int max_sum = INT_MIN;
for (int i=0; i<R-2; i++)
{
for (int j=0; j<C-2; j++)
{
// Considering mat[i][j] as top left cell of
// hour glass.
int sum = (mat[i][j]+mat[i][j+1]+mat[i][j+2])+
(mat[i+1][j+1])+
(mat[i+2][j]+mat[i+2][j+1]+mat[i+2][j+2]);

// If previous sum is less then current sum then
// update new sum in max_sum
max_sum = max(max_sum, sum);
}
}
return max_sum;
}

// Driver code
int main()
{
int mat[][C] = {{1, 2, 3, 0, 0},
{0, 0, 0, 0, 0},
{2, 1, 4, 0, 0},
{0, 0, 0, 0, 0},
{1, 1, 0, 1, 0}};
int res = findMaxSum(mat);
if (res == -1)
cout << "Not possible" << endl;
else
cout << "Maximum sum of hour glass = "
<< res << endl;
return 0;
}
```

Output:

```Maximum sum of hour glass = 13
```

This article is contributed by DANISH_RAZA . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
1.7 Average Difficulty : 1.7/5.0
Based on 7 vote(s)