Dungeon Game LeetCode solution in JavaScript

1
/**
2
* The dynamic programming solution.
3
*
4
* Time Complexity: O(m*n)
5
* Space Complexity: O(1)
6
*
7
* @param {number[][]} dungeon
8
* @return {number}
9
*/
10
var calculateMinimumHP = function (dungeon) {
11
const m = dungeon.length;
12
const n = dungeon[0].length;
13

14
const ii = m - 1;
15
const jj = n - 1;
16

17
for (let i = ii; i >= 0; i--) {
18
for (let j = jj; j >= 0; j--) {
19
if (i < ii || j < jj) {
20
const hc = dungeon[i][j];
21

22
const hp1 = i < ii ? Math.min(hc, hc + dungeon[i + 1][j]) : -Infinity;
23
const hp2 = j < jj ? Math.min(hc, hc + dungeon[i][j + 1]) : -Infinity;
24

25
dungeon[i][j] = Math.max(hp1, hp2);
26
}
27
}
28
}
29

30
return Math.max(1 - dungeon[0][0], 1);
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0