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.

A Javascript solution using O(n*m) time complexity and O(1) space complexity.

functionhourGlass(arr){// we could set this to 3 given the problems constraings, but this allows changesmaxX=3;// + (arr[0].length % 3)maxY=3;// + (arr.length % 3)total=-Infinity;// has to be -64, but// begin at y == 0for(lety=0;y<=maxY;y++){for(letx=0;x<=maxX;x++){// sum the top of hourglassletsum=arr[y][x]+arr[y][x+1]+arr[y][x+2];// get the middle of hourglasssum+=arr[y+1][x+1];// sum the bottom of hourglasssum+=arr[y+2][x]+arr[y+2][x+1]+arr[y+2][x+2]// don't store result to keep space complexity downif(total<sum)total=sum;}}returntotal;}

You can't set the initial value of 'total' to 0, because the answer might be lower. To avoid that, set the initial value to the lowest possible (-infinity).

The smallest number allowable for any of the numbers in the hourglass is -9. If all the numbers in an hourglass are -9, the lowest possible value for an hourglass is -63. So an initial value of -63 is ok too.

## 2D Array - DS

You are viewing a single comment's thread. Return to all comments →

A Javascript solution using

`O(n*m)`

time complexity and`O(1)`

space complexity.Hey awesome solution, just a quick question why use -Infinity

You can't set the initial value of 'total' to 0, because the answer might be lower. To avoid that, set the initial value to the lowest possible (-infinity).

The smallest number allowable for any of the numbers in the hourglass is -9. If all the numbers in an hourglass are -9, the lowest possible value for an hourglass is -63. So an initial value of -63 is ok too.

you can also use -64 since the lowest possible value is -63 :)

take a bow ..salute to ur code

Similar JavaScript solution:

Hi, why are you setting max value as -63?? why dont set first value a max and compare consequetive sum's??

(-9 * 7) -63 is the lowest possible value. You could set the max to the first value or even undefined if you wanted (style choice).