-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.go
48 lines (43 loc) · 1.09 KB
/
Solution.go
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
package lc45
// Greedy solution. O(n)
// Greedy Choice property:
// Let nums[i]* be the jump that reaches the furthest index, such that
// i + nums[i]* = max(j + nums[j]) for all 0<=j<=len(nums)
// Then, there exists an optimal solution which includes nums[i]*.
func Jump(nums []int) int {
jumps := 1
furthest := nums[0] // represents the current furthest index reachable with the number of jumps
for i := 1; i < len(nums); i++ {
if i > furthest {
// Cannot reach the end
return 0
}
if i+nums[i] > furthest {
jumps++
furthest = i + nums[i]
}
if furthest >= len(nums)-1 {
// Can already reach last index
break
}
}
return jumps
}
// Naive DP solution. O(n^2)
func jumpNaive(nums []int) int {
dp := make([]int, len(nums))
// dp[i] represents the minimum number of jumps required to reach the i-th position.
for i := 0; i < len(nums); i++ {
dp[i] = 10000 // 0 <= nums[i] <= 1000
}
dp[0] = 0
for i, jumpLength := range nums {
for j := 1; j <= jumpLength; j++ {
if i+j >= len(nums) {
break
}
dp[i+j] = min(1+dp[i], dp[i+j])
}
}
return dp[len(nums)-1]
}