Wednesday, July 8, 2020

Hour glass Sum

Hour glass sum for 6*6 matrix

There are  hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.

For example, given the 2D array:

-9 -9 -9 1 1 1 

 0 -9 0 4 3 2

-9 -9 -9 1 2 3

 0 0 8 6 6 0

 0 0 0 -2 0 0

 0 0 1 2 4 0

We calculate the following  hourglass values:

-63, -34, -9, 12, 

-10, 0, 28, 23, 

-27, -11, -2, 10, 

9, 17, 25, 18

Our highest hourglass value is  from the hourglass:

0 4 3

  1

8 6 6

Input Format

Each of the  lines of inputs  contains  space-separated integers .

Constraints

  • -9 <= arr[i][j] 9
  • 0 <= i,j <= 5

Output Format

Print the largest (maximum) hourglass sum found in .

Solution:

//code by anewbieprogrammer

#include <iostream>
using namespace std;
const int R = 6;
const int C = 6;

int hourglassSum(int mat[][C]){
    if(R < 3 || C < 3)
        return -1;
    int sum = 0;
    int max_sum = -63;
    for(int r = 0; r < R-2; r++){
        for(int c = 0; c < C-2; c++){
            sum = mat[r][c] + mat[r][c+1] + mat[r][c+2]
                        + mat[r+1][c+1]
                        + mat[r+2][c] + mat[r+2][c+1] + mat[r+2][c+2];

            if(max_sum < sum) max_sum = sum;
        }       
    }
return max_sum;
}

int main(){
    int mat[R][C];
    int r, c;
    for(r = 0; r < R; r++){
        for(c = 0; c < C; c++){
            cin>>mat[r][c];
        }            
    }
    int s = hourglassSum(mat);
    if(s == -1)
        cout<<"not possible";
    else
        cout<<s;
    return 0;
}

No comments:

Post a Comment

horizontal ads