# Maximum sum of hour glass in matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a matrix. Our task is to create a program that finds the maximum sum of the hourglass in a matrix in C++.

Program description − Here, we will find the maximum sum of all hourglasses that can be created for the given matrix elements.

Hour glass is a 7 element shape made in the matrix in the following form,

X X X
X
X X X

Let’s take an example to understand the problem,

Input

array ={
{2 4 0 0}
{0 1 1 0}
{4 2 1 0}
{0 3 0 1}}

Output

Explanation

Hour glass are :
2    4    0       0    1    1
1                 2
4    2    1       0    3    0
4    0    0       1    1    0
1                 1
2    1    0       3    0    1

So, an hourglass can be created using the following indexes,

matrix[i][j]    matrix[i][j+1]    matrix[i][j+2]
matrix[i+1][j+1]
matrix[i+2][j] matrix[i+2][j+1]   matrix[i+2][j+2]

We will find the sum of all these elements of the array from  to [R2][C-2] starting points. And the find the maxSum for all these hourglasses created from array elements.

## Example

Program to illustrate the working of our solution,

Live Demo

#include<iostream>
using namespace std;
const int row = 4;
const int col = 4;
int findHourGlassSum(int mat[row][col]){
if (row<3 || col<3)
return -1;
int maxSum = 0;
for (int i=0; i<row-2; i++){
for (int j=0; j<col-2; j++){
int hrSum = (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]);
maxSum = max(maxSum, hrSum);
}
}
return maxSum;
}
int main() {
int mat[row][col] = {
{2, 4, 0, 0},
{0, 1, 1, 0},
{4, 2, 1, 0},
{0, 3, 0, 1}};
int maxSum = findHourGlassSum(mat);
if (maxSum == -1)
cout<<"Not possible";
else
cout<<"Maximum sum of hour glass created is "<<maxSum;
return 0;
}

## Output

Maximum sum of hour glass created is 14