-
Notifications
You must be signed in to change notification settings - Fork 1
/
hourGlass.js
45 lines (39 loc) · 896 Bytes
/
hourGlass.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
*
* Hourglass Sum
*
* @param {number[]} arr
* @return {number}
*/
function hourglassSum(arr) {
let max = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < arr.length - 2; i++) {
for (let j = 0; j < arr[i].length - 2; j++) {
let 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];
max = Math.max(sum, max);
}
}
return max;
}
// Test
if (require.main === module) {
console.log(hourglassSum([
[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 9, 2, -4, -4, 0],
[0, 0, 0, -2, 0, 0],
[0, 0, -1, -2, -4, 0]
])); // 13
console.log(hourglassSum([
[-1, 1, -1, 0, 0, 0],
[0, -1, 0, 0, 0, 0],
[-1, -1, -1, 0, 0, 0],
[0, -9, 2, -4, -4, 0],
[-7, 0, 0, -2, 0, 0],
[0, 0, -1, -2, -4, 0]
]))
}
module.exports = {
hourglassSum
};