Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The longest rise-then-fall subsequence

Medium · Target 20 minutes · Dynamic programming

A sequence is bitonic if it strictly increases and then strictly decreases (either part may be empty). Given nums, return the length of its longest bitonic subsequence.

Examples

InputOutputWhy
nums = [1,11,2,10,4,5,2,1]61, 2, 10, 4, 2, 1.
nums = [12,11,40,5,3,1]512, 40, 5, 3, 1.
nums = [80,60,30,40,20,10]580, 60, 40, 20, 10: no rise at all.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • −10⁶ ≤ nums[i] ≤ 10⁶

Hints

Hint 1

A bitonic subsequence has a peak. Fix the peak position i.

Hint 2

up[i] = longest increasing subsequence ending at i (from the left); down[i] = longest decreasing subsequence starting at i (an increasing one from the right).

Hint 3

The answer is the maximum of up[i] + down[i] − 1.

Where people lose marks

  • Forgetting the − 1 for the shared peak.
  • Requiring both parts to be non-empty when the problem allows a purely increasing or decreasing sequence.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.