-
Notifications
You must be signed in to change notification settings - Fork 1
/
376.摆动序列.go
82 lines (79 loc) · 1.98 KB
/
376.摆动序列.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
74
75
76
77
78
79
80
/*
* @lc app=leetcode.cn id=376 lang=golang
*
* [376] 摆动序列
*
* https://leetcode-cn.com/problems/wiggle-subsequence/description/
*
* algorithms
* Medium (37.16%)
* Likes: 60
* Dislikes: 0
* Total Accepted: 3.3K
* Total Submissions: 8.8K
* Testcase Example: '[1,7,4,9,2,5]'
*
* 如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
*
* 例如, [1,7,4,9,2,5] 是一个摆动序列,因为差值 (6,-3,5,-7,3) 是正负交替出现的。相反, [1,4,7,2,5] 和
* [1,7,4,5,5] 不是摆动序列,第一个序列是因为它的前两个差值都是正数,第二个序列是因为它的最后一个差值为零。
*
* 给定一个整数序列,返回作为摆动序列的最长子序列的长度。 通过从原始序列中删除一些(也可以不删除)元素来获得子序列,剩下的元素保持其原始顺序。
*
* 示例 1:
*
* 输入: [1,7,4,9,2,5]
* 输出: 6
* 解释: 整个序列均为摆动序列。
*
*
* 示例 2:
*
* 输入: [1,17,5,10,13,15,10,5,16,8]
* 输出: 7
* 解释: 这个序列包含几个长度为 7 摆动序列,其中一个可为[1,17,10,13,10,16,8]。
*
* 示例 3:
*
* 输入: [1,2,3,4,5,6,7,8,9]
* 输出: 2
*
* 进阶:
* 你能否用 O(n) 时间复杂度完成此题?
*
*/
func wiggleMaxLength(nums []int) int {
n := len(nums)
if n <= 0 {
return 0
}
ups := make([]int, n)
downs := make([]int, n)
ups[0] = 1
downs[0] = 1
result := 1
for i := 1; i < n; i++ {
up := 0
for j := i - 1; j >= 0; j-- {
if nums[i] > nums[j] {
up = max(up, downs[j])
}
}
ups[i] = up + 1
down := 0
for j := i - 1; j >= 0; j-- {
if nums[i] < nums[j] {
down = max(down, ups[j])
}
}
downs[i] = down + 1
result = max(result, max(ups[i], downs[i]))
}
return result
}
func max(a, b int) int {
if a > b {
return a
}
return b
}