Longest alternating subsequence
Pattern: LIS family
In an alternating subsequence the differences switch sign each step. Keep up (the longest one ending with a rise) and down (ending with a fall); a rise extends down, a fall extends up.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Return the length of the longest subsequence of nums whose consecutive differences strictly alternate between positive and negative (equal neighbours are not allowed).
Think first
- What must you know about the end of a subsequence?
- What does a rise extend?
- What about equal values?
Hints
Brute force, and why it fails
LIS-style DP with two states per index: O(n²).
The key insight
Only the best up-ending and down-ending lengths so far matter, so two numbers are enough.
Dry run
| up | 1 |
|---|---|
| down | 1 |
[1, 5, 4]. Start: up = down = 1.
Step 1 of 3
The plan
up = down = 1
for i: if a[i] > a[i-1]: up = down + 1
elif a[i] < a[i-1]: down = up + 1
return max(up, down)
Complexity
- Time
O(n)- Space
O(1)
One pass.
Edge cases
- One value: 1.
- All equal: 1.
- Strictly increasing: 2.
I've built my logic, show the code
Java
class Solution {
public int AlternatingaMaxLength(int[] nums) {
int up = 1, down = 1; // the longest alternating run ending with a rise / with a fall
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[i - 1]) up = down + 1; // a rise extends a run that last fell
else if (nums[i] < nums[i - 1]) down = up + 1; // a fall extends a run that last rose
}
return Math.max(up, down);
}
}C++
class Solution {
public:
int AlternatingaMaxLength(vector<int>& nums) {
int up = 1, down = 1; // the longest alternating run ending with a rise / with a fall
for (size_t i = 1; i < nums.size(); i++) {
if (nums[i] > nums[i - 1]) up = down + 1; // a rise extends a run that last fell
else if (nums[i] < nums[i - 1]) down = up + 1; // a fall extends a run that last rose
}
return max(up, down);
}
};Python
class Solution:
def AlternatingaMaxLength(self, nums: list[int]) -> int:
up = down = 1 # the longest alternating run ending with a rise / with a fall
for a, b in zip(nums, nums[1:]):
if b > a:
up = down + 1 # a rise extends a run that last fell
elif b < a:
down = up + 1 # a fall extends a run that last rose
return max(up, down)Common mistakes
- Counting equal neighbours.
- Starting at 0.