Skip to content

Commit 6320969

Browse files
authored
Create 45-jump-game-ii.js
1 parent f8bd65d commit 6320969

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

45-jump-game-ii.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const jump = function(nums) {
6+
if (nums.length <= 1) return 0;
7+
let curMax = 0; // to mark the last element in a level
8+
let level = 0, i = 0;
9+
while (i <= curMax) {
10+
let furthest = curMax; // to mark the last element in the next level
11+
for (; i <= curMax; i++) {
12+
furthest = Math.max(furthest, nums[i] + i);
13+
if (furthest >= nums.length - 1) return level + 1;
14+
}
15+
level++;
16+
curMax = furthest;
17+
}
18+
return -1; // if i < curMax, i can't move forward anymore (the last element in the array can't be reached)
19+
};

0 commit comments

Comments
 (0)