-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
44 lines (41 loc) · 1.01 KB
/
Solution.cs
File metadata and controls
44 lines (41 loc) · 1.01 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
public class Solution
{
public int Jump(int[] nums)
{
return Jump_Greedy(nums);
// return Jump_DP(nums);
}
private int Jump_Greedy(int[] nums)
{
int n = nums.Length;
if (n == 1) return 0;
int jumps = 0;
int current = 0;
int furthest = 0;
for (int i = 0; i < n - 1; i++)
{
furthest = Math.Max(furthest, i + nums[i]);
if (i == current)
{
jumps++;
current = furthest;
if (current >= n - 1) break;
}
}
return jumps;
}
private int Jump_DP(int[] nums)
{
int[] dp = new int[nums.Length];
Array.Fill(dp, nums.Length);
dp[0] = 0;
for (int i = 0; i < nums.Length - 1; i++)
{
for (int j = 1; j <= nums[i] && (i + j) < nums.Length; j++)
{
dp[i + j] = Math.Min(dp[i + j], dp[i] + 1);
}
}
return dp[nums.Length - 1];
}
}