You are viewing a single comment's thread. Return to all comments →
C++11.
We need to:
Traverse a 6x6 2D array.
For each possible “hourglass” (shape of 7 cells), calculate its sum.
Track and return the maximum sum.
Here’s a clean solution:
using namespace std;
int hourglassSum(vector> arr) { int maxSum = INT_MIN; // since values can be negative
for (int i = 0; i <= 3; i++) { for (int j = 0; j <= 3; j++) { int sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] // top row + arr[i+1][j+1] // middle + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2]; // bottom row maxSum = max(maxSum, sum); } } return maxSum;
}
int main() { vector> arr(6, vector(6)); for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { cin >> arr[i][j]; } } cout << hourglassSum(arr) << endl; return 0; }
✅ Explanation:
We only go up to index 3 (not 5), since an hourglass needs 3 rows and 3 columns.
At each (i, j), we compute the hourglass sum.
Keep updating maxSum.
Return the largest sum found.
🔹 For the sample input in your problem, this outputs 19.
Seems like cookies are disabled on this browser, please enable them to open this website
2D Array - DS
You are viewing a single comment's thread. Return to all comments →
C++11.
We need to:
Traverse a 6x6 2D array.
For each possible “hourglass” (shape of 7 cells), calculate its sum.
Track and return the maximum sum.
Here’s a clean solution:
include
using namespace std;
int hourglassSum(vector> arr) { int maxSum = INT_MIN; // since values can be negative
}
int main() { vector> arr(6, vector(6)); for (int i = 0; i < 6; i++) { for (int j = 0; j < 6; j++) { cin >> arr[i][j]; } } cout << hourglassSum(arr) << endl; return 0; }
✅ Explanation:
We only go up to index 3 (not 5), since an hourglass needs 3 rows and 3 columns.
At each (i, j), we compute the hourglass sum.
Keep updating maxSum.
Return the largest sum found.
🔹 For the sample input in your problem, this outputs 19.