-
Notifications
You must be signed in to change notification settings - Fork 0
/
wiggleSubsequence.go
56 lines (52 loc) · 981 Bytes
/
wiggleSubsequence.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
package golang
// Wiggle Subsequence
// leetCode: https://leetcode-cn.com/problems/wiggle-subsequence/
func WiggleSubsequence(nums []int) int {
n := len(nums)
if n < 2 {
return n
}
up := make([]int, n)
down := make([]int, n)
up[0] = 1
down[0] = 1
for i := 1; i < n; i++ {
if nums[i] > nums[i-1] {
up[i] = max(up[i-1], down[i-1]+1)
down[i] = down[i-1]
}else if nums[i] < nums[i-1] {
down[i] = max(up[i-1]+1, down[i-1])
up[i] = up[i-1]
}else {
up[i] = up[i-1]
down[i] = down[i-1]
}
}
return max(up[n-1], down[n-1])
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func WiggleSubsequence2(nums []int) (I int) {
var previous string
if len(nums) < 2 {
return len(nums)
}
I = 1
for i := 0; i < len(nums); i++ {
if i == len(nums) - 1 {
break
}
if nums[i] - nums[i+1] < 0 && previous != "N" {
previous = "N"
I++
}else if nums[i] - nums[i+1] > 0 && previous != "P" {
previous = "P"
I++
}
}
return
}