Promble
Link: https://leetcode.com/problems/wiggle-subsequence/description/
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative. In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array nums, return the length of the longest wiggle subsequence of nums.
Input: nums = [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length.
One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).
Input: nums = [1,2,3,4,5,6,7,8,9]
Output: 2
📓 see in PKSHA code test.
Approach 1
DP method
Thought
- init the status
- p = [1] * size, is the increase list.
- q = [1] * size, is the de-increase list.
- i loop the size index, from 1 start
- j loop in i
- if nums[i] > nums[j]: p[i] = max(p[i], q[j]+1). update the p list with max between p[i] and q[j]+1
- if nums[i] < nums[j]: q[j] = max(q[i], p[j]+1). update the q list with max between q[i] and p[j]+1
- if nums[i] == nums[j]: dont update the list
- return the max number in last index of p and q.
Code
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if nums == []:
return 0
size = len(nums)
# init the status
p = [1] * size
q = [1] * size
for i in range(1, size):
for j in range(i):
if nums[i] > nums[j]:
p[i] = max(p[i], q[j]+1)
elif nums[i] < nums[j]:
q[i] = max(q[i], p[j]+1)
return max(p[size-1], q[size-1])
Complexity
时间复杂度 $O(n^2)$, two for loop
空间复杂度 $O(2)$,p and q is list
Approach 2
DP mthod 2
Thought
- if len(nums) < 2: return len(nums)
- def inc_len and dec_len, to store the length of increase list and decrease list.
- i, loop in nums, from 1 to len(nums).
- nums[i] has 3 status:
- if nums[i] > nums[i-1]: inc_len = dec_len + 1.
- if nums[i] < nums[i-1]: dec_len = inc_len + 1.
- if nums[i] == nums[i-1]: dont update inc_len or dec_len.
- return the max of the inc_len and dec_len.
Code
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
if len(nums) < 2:
return len(nums)
inc_len, dec_len = 1, 1
for i in range(1, len(nums)):
if nums[i] > nums[i-1]:
inc_len = dec_len+1
elif nums[i] < nums[i-1]:
dec_len = inc_len+1
else:
pass
return max(inc_len, dec_len)
Complexity
时间复杂度 $O(n)$
空间复杂度 $O(1)$,two int value.