Longest Zigzag Subsequence
Problem Description
A **zigzag sequence** is a sequence of integers where the signs of the differences alternate — i.e., every pair of adjacent elements alternates between strictly increasing and strictly decreasing.
More formally, a subsequence `a[0], a[1], ..., a[k]` is zigzag if:
- `a[1] > a[0]`, `a[2] < a[1]`, `a[3] > a[2]`, ... (starts with rise), OR
- `a[1] < a[0]`, `a[2] > a[1]`, `a[3] < a[2]`, ... (starts with fall).
Given an integer array `sequence`, return the length of the **longest zigzag subsequence**.
A single element or two strictly different elements are trivially zigzag.
**Example 1:**
```
Input: sequence = [1, 7, 4, 9, 2, 5]
Output: 6
```
**Explanation:** The entire array [1,7,4,9,2,5] is already zigzag (rises and falls alternate), so the answer is 6.
**Example 2:**
```
Input: sequence = [1, 4, 7, 2, 5]
Output: 4
```
**Explanation:** The longest zigzag subsequence is [1,7,2,5] or [1,4,2,5], both of length 4.
Constraints
- 1 <= sequence.length <= 1000
- -10^4 <= sequence[i] <= 10^4
Follow-up
Can you also return the actual indices forming the longest zigzag subsequence, not just its length?
Hints
Try the problem first. If you get stuck, you can reveal hints one at a time.
Solution
Leaderboard
No entries yet for python.
Be the first — submit an accepted solution.