Skip to content

Instantly share code, notes, and snippets.

@hmenn
Created March 2, 2019 19:40
Show Gist options
  • Save hmenn/5d787d3210ddc7bf9d8178d2425bf585 to your computer and use it in GitHub Desktop.
Save hmenn/5d787d3210ddc7bf9d8178d2425bf585 to your computer and use it in GitHub Desktop.
hackerrank - interview kit - 2d arrays
/*
Given a 2D Array, :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation:
a b c
d
e f g
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.
*/
int hourglassSum(vector<vector<int>> arr) {
int max =numeric_limits<int>::min();
for(int i=0; i<arr.size()-2;++i){
for(int j=0; j< arr[i].size()-2; ++j){
int sumUpSide = arr[i][j]+arr[i][j+1]+arr[i][j+2];
int sumMiddle = arr[i+1][j+1];
int sumDownSide = arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
int sum = sumUpSide + sumMiddle + sumDownSide;
if(sum>max){
max=sum;
}
}
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment