We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Different and Simple approach.
code in C++.
Logic:
- First we find all the possible 3X3 matrices and their sum
- Then we subtract those particular two elements from the 3X3 matrix sum so that we get sum of hourglass indirectly.
- And compare them for maximum sum.
Et voila!
Sometimes we have to look at the problem with a different perspective.
My Code:
int main(){
vector< vector<int> > arr(6,vector<int>(6));
for(int arr_i = 0;arr_i < 6;arr_i++){
for(int arr_j = 0;arr_j < 6;arr_j++){
cin >> arr[arr_i][arr_j];
}
}
int sumhour=-1000,sum=0; //sumhour intialized for negative value so to calculate sum for negative numbers
for(int iog=0;iog<4;iog++) //for loop to generate first element of all 3X3 matrices possible
{
for(int jog=0;jog<4;jog++) //for loop to generate first element of all 3X3 matrices possible
{
sum=0;
for(int i=iog;i<iog+3;i++) //to access all other members of 3X3 matrix
{
for(int j=jog;j<jog+3;j++) //to access all other members of 3X3 matrix
{
sum=sum+arr[i][j]; //sum of 3X3 matrix
}
}
sum=sum-arr[iog+1][jog]-arr[iog+1][jog+2]; //here we subtract those two elements from 3X3 which are not included in hourglass
if(sum>sumhour) sumhour=sum;
}
}
cout<<sumhour;
return 0;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 11: 2D Arrays
You are viewing a single comment's thread. Return to all comments →
Different and Simple approach. code in C++. Logic: - First we find all the possible 3X3 matrices and their sum - Then we subtract those particular two elements from the 3X3 matrix sum so that we get sum of hourglass indirectly. - And compare them for maximum sum.
Et voila! Sometimes we have to look at the problem with a different perspective.
My Code: