Skip to content
Advertisement

Java – How to Solve this 2D Array Hour Glass?

I am working on a problem where I’ve to print the largest sum among all the hourglasses in the array. You can find the details about the problem here-

What I tried:

JavaScript

Input:

JavaScript

Output:

JavaScript

Expected Output:

JavaScript

Screenshot: enter image description here

I don’t know where I’m doing wrong. I cannot understand why the expected output is 13. According to the description given in the problem it should be 10. Is this a wrong question or my understanding about this is wrong?

Advertisement

Answer

Remove the if (arr[arr_i][arr_j] > 0) statement. It prevents finding the answer at row 1, column 0, because that cell is 0.

Comments for other improvements to your code:

  • What if the best hourglass sum is -4? You should initialize tmp_sum to Integer.MIN_VALUE. And name it maxSum, to better describe it’s purpose.

  • You shouldn’t define sum outside the loop. Declare it when it is first assigned, then you don’t have to reset it to 0 afterwards.

  • Your iterators should be just i and j. Those are standard names for integer iterators, and keeps code … cleaner.
    If you prefer longer names, use row and col, since that is what they represent.

  • You don’t need parenthesis around the array lookups.

  • For clarity, I formatted the code below to show the hourglass shape in the array lookups.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement