Wiggle Subsequence — LeetCode 376 Python Solution
MediumGreedyArrayDynamic Programming
- Problem
- #376
- Pattern
- Greedy
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- 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).
Python solution
Python
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
n = len(nums)
ans = 1
f = [1] * n
g = [1] * n
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]:
f[i] = max(f[i], g[j] + 1)
elif nums[j] > nums[i]:
g[i] = max(g[i], f[j] + 1)
ans = max(ans, f[i], g[i])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 376. Wiggle Subsequence is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 376. Wiggle Subsequence?
- LeetCode 376. Wiggle Subsequence is rated Medium on LeetCode.
- What is the time complexity of LeetCode 376. Wiggle Subsequence?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 376. Wiggle Subsequence?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 376. Wiggle Subsequence cover?
- LeetCode 376. Wiggle Subsequence is tagged Greedy, Array and Dynamic Programming on LeetCode.