-
Notifications
You must be signed in to change notification settings - Fork 43
/
wiggle-subsequence.py
91 lines (84 loc) · 2.32 KB
/
wiggle-subsequence.py
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
81
82
83
84
85
86
87
88
89
90
91
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82902655
# IDEA : DP
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n <= 1:
return n
inc, dec = [1] * n, [1] * n
for x in range(n):
for y in range(x):
if nums[x] > nums[y]:
inc[x] = max(inc[x], dec[y] + 1)
elif nums[x] < nums[y]:
dec[x] = max(dec[x], inc[y] + 1)
return max(inc[-1], dec[-1])
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/82902655
# IDEA : DP
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n <= 1:
return n
inc, dec = [1] * n, [1] * n
for x in range(1, n):
if nums[x] > nums[x - 1]:
inc[x] = dec[x - 1] + 1
dec[x] = dec[x - 1]
elif nums[x] < nums[x - 1]:
inc[x] = inc[x - 1]
dec[x] = inc[x - 1] + 1
else:
inc[x] = inc[x - 1]
dec[x] = dec[x - 1]
return max(inc[-1], dec[-1])
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/82902655
# IDEA : DP
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n <= 1:
return n
inc, dec = 1, 1
for x in range(1, n):
if nums[x] > nums[x - 1]:
inc = dec + 1
elif nums[x] < nums[x - 1]:
dec = inc + 1
return max(inc, dec)
# V2
# Time: O(n)
# Space: O(1)
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) < 2:
return len(nums)
length, up = 1, None
for i in range(1, len(nums)):
if nums[i - 1] < nums[i] and (up is None or up is False):
length += 1
up = True
elif nums[i - 1] > nums[i] and (up is None or up is True):
length += 1
up = False
return length