Longest Alternating Up-Down Subsequence in Daily Price Changes
Last updated: November 29, 2026
Quick Overview
Given a product's daily prices, find the length of the longest subsequence (not necessarily contiguous) in which successive differences strictly alternate between rising and falling. A single day counts as length 1, and two different prices count as length 2.
Amazon
November 29, 20260
0
0 solved
Given a product's daily prices, find the length of the longest subsequence (not necessarily contiguous) in which successive differences strictly alternate between rising and falling. A single day counts as length 1, and two different prices count as length 2.
An Amazon technical screen question where an O(n^2) DP is easy to find and the interviewer pushes for the O(n) greedy. They want you to argue why counting direction changes, while skipping flat days, gives the optimum.
What the Interviewer Expects
- Gives the O(n^2) DP as a baseline
- Reduces to counting turning points
- Ignores zero differences
- Tracks the previous nonzero direction
- Runs in O(n) time and O(1) space
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Return the subsequence itself.
- Require each move to be at least some threshold t in size.
- What if you need the longest contiguous alternating run instead?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: list of integers, length up to 10^5. Output: length of the longest subsequence whose consecutive differences alternate strictly in sign (zero differences are not allowed in the subsequence)....
High-Level Design
A DP with up[i] and down[i] (best length ending at i with a last move up or down) works in O(n^2), and it collapses to O(n) with two running values: on a rise, up = down + 1; on a fall, down = up + 1....