Wiggle Subsequence
The key idea
Problem
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if it exists) may be either positive or negative. A sequence with one element or two unequal elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) alternate in sign. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences: the first has two consecutive positive differences, and the second has its last difference equal to 0.
A subsequence is obtained by deleting some (possibly zero) elements from the original sequence while leaving the remaining elements in their original order.
Given an integer array nums, return the length of the longest wiggle subsequence of nums.
Constraints
- 1 <= nums.length <= 1000
- 0 <= nums[i] <= 1000
Examples
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Greedy problems
- Assign CookiesEASY
- Best Time to Buy and Sell Stock IIMEDIUM
- Boats to Save PeopleMEDIUM
- Can Place FlowersEASY
- CandyHARD
- Dota2 SenateMEDIUM
- Gas StationMEDIUM
- Hand of StraightsMEDIUM
- Increasing Triplet SubsequenceMEDIUM
- Jump GameMEDIUM
- Jump Game IIMEDIUM
- Lemonade ChangeEASY