-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJump_Game_II.cpp
More file actions
33 lines (27 loc) · 801 Bytes
/
Jump_Game_II.cpp
File metadata and controls
33 lines (27 loc) · 801 Bytes
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
// https://leetcode.com/problems/jump-game-ii/
// Approach: https://www.youtube.com/watch?v=hZkb_Dqu7YY
/*
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
*/
class Solution {
public:
int jump(vector<int>& nums)
{
int n = nums.size();
if(n <= 1)
return 0;
int ans = 1, end = nums[0], lim = nums[0];
for(int i = 0; i < n; i++)
{
if(i > lim)
{
ans++;
lim = end;
}
end = max(end, i + nums[i]);
}
return ans;
}
};