forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0045-jump-game-ii.js
More file actions
50 lines (41 loc) · 1.07 KB
/
0045-jump-game-ii.js
File metadata and controls
50 lines (41 loc) · 1.07 KB
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
46
47
48
49
50
/**
* https://leetcode.com/problems/jump-game-ii/
* Time O(N) | Space O(1)
* @param {number[]} nums
* @return {number}
*/
var jump = function (nums) {
let [left, right, jumps] = [0, 0, 0];
while (right < nums.length - 1) {
const maxReach = getMaxReach(nums, left, right);
left = right + 1;
right = maxReach;
jumps += 1;
}
return jumps;
};
const getMaxReach = (nums, left, right, maxReach = 0) => {
for (let i = left; i < right + 1; i++) {
const reach = nums[i] + i;
maxReach = Math.max(maxReach, reach);
}
return maxReach;
};
/**
* https://leetcode.com/problems/jump-game-ii/
* Time O(N) | Space O(1)
* @param {number[]} nums
* @return {number}
*/
var jump = function (nums) {
let [jumps, currentJumpEnd, farthest] = [0, 0, 0];
for (let i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
const canJump = i === currentJumpEnd;
if (canJump) {
jumps++;
currentJumpEnd = farthest;
}
}
return jumps;
};