Wiggle Subsequence
Problem: Wiggle Subsequence
When we are scanning the array, if we are going down, we should try to reach lowest possible consecutive number. For example, if the sequence looks like [3,2,1,2,0], we should going down to 1 so that we can go up at 2. If we go down to 3 and stop going down, we cannot reach longer subsequence. Also when we are going up, we should also try to reach largest possible consecutive number.
Code in Python:
class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
direction, res = 0, 1
for i in xrange(1, len(nums)):
if direction == 0:
if nums[i] != nums[i-1]: res += 1
if nums[i] > nums[i-1]: direction = 1
elif nums[i] < nums[i-1]: direction = -1
elif nums[i] < nums[i-1] and direction == 1:
res += 1
direction = -1
elif nums[i] > nums[i-1] and direction == -1:
res += 1
direction = 1
return res