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 alternating subsequence

Medium · Target 20 minutes · Dynamic programming · Type asked atGoogle

A sequence wiggles if the differences between successive elements are strictly positive and strictly negative in turn (the first difference may be either). A single element wiggles trivially. Given nums, return the length of its longest wiggling subsequence.

Examples

InputOutputWhy
nums = [1,7,4,9,2,5]6The whole list wiggles.
nums = [1,17,5,10,13,15,10,5,16,8]7For example 1, 17, 10, 13, 10, 16, 8.
nums = [1,2,3,4,5,6,7,8,9]2Any rise: one up-step.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000

Hints

Hint 1

Two states per position: the longest wiggle ending here with an up-step, and with a down-step.

Hint 2

An up-step at i extends a down-ending wiggle; a down-step extends an up-ending one.

Hint 3

Only the best values so far matter, so two variables are enough.

Where people lose marks

  • Counting zero differences as wiggles.
  • Starting up and down at 0 instead of 1 (a single element is a wiggle of length 1).
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.