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.
This is my solution. I feel like the use of a new sum array is not needed. The reason why max = -64 is because each term in the 2D array is: -9 <= A[i][j] <= 9. Since an hourglass has 7 terms, the lowest sum possible is -63. Therefore, the sum will always be greater than the max and change the max to be the greatest sum.
int sum, max = -64;
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
sum = arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1] + arr[i+2][j+2];
if (sum > max){
max = sum;
}
}
}
System.out.println(max);
If there is any way to make my code more efficient or clearer to understand, please let me know.
Thanks!
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 →
This is my solution. I feel like the use of a new sum array is not needed. The reason why max = -64 is because each term in the 2D array is: -9 <= A[i][j] <= 9. Since an hourglass has 7 terms, the lowest sum possible is -63. Therefore, the sum will always be greater than the max and change the max to be the greatest sum.
If there is any way to make my code more efficient or clearer to understand, please let me know. Thanks!