-
Notifications
You must be signed in to change notification settings - Fork 481
/
1340.go
73 lines (65 loc) · 1.35 KB
/
1340.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
var dp, lb, rb []int
var n, td int
func maxJumps(arr []int, d int) int {
n, td = len(arr), d
dp = make([]int, n)
lb = make([]int, n)
rb = make([]int, n)
for i := 0; i < n; i++ {
lb[i], rb[i] = -1, -1
}
findBiggerLeft(arr)
findBiggerRight(arr)
res := 0
for i := 0; i < n; i++ {
res = max(res, dfs(i))
}
return res
}
func findBiggerLeft(arr []int) {
s := []int{}
for i := 0; i < n; i++ {
for len(s) > 0 && s[0] < i - td {
s = s[1:]
}
for len(s) > 0 && arr[s[len(s)-1]] <= arr[i] {
s = s[:len(s)-1]
}
if len(s) > 0 {
lb[i] = s[len(s) - 1]
}
s = append(s, i)
}
}
func findBiggerRight(arr []int) {
s := []int{}
for i := 0; i < n; i++ {
for len(s) > 0 && s[0] < i - td {
s = s[1:]
}
for len(s) > 0 && arr[s[len(s) - 1]] < arr[i] {
rb[s[len(s) - 1]] = i
s = s[:len(s) - 1]
}
s = append(s, i)
}
}
func dfs(u int) int {
if dp[u] > 0 {
return dp[u]
}
dp[u] = 1
if lb[u] >= 0 {
dp[u] = max(dp[u], dfs(lb[u]) + 1)
}
if rb[u] >= 0 {
dp[u] = max(dp[u], dfs(rb[u]) + 1)
}
return dp[u]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}