Greedy Algorithms8 sections · 316 units
Open in Course

Problem - Wiggle Subsequence

Alternating differences

Find the longest subsequence where differences alternate between positive and negative. For [1,7,4,9,2,5][1,7,4,9,2,5], the answer is 66 (the whole array works: differences are +6,3,+5,7,+3+6, -3, +5, -7, +3). For [1,17,5,10,13,15,10,5,16,8][1,17,5,10,13,15,10,5,16,8], answer is 77. Count peaks and valleys in the sequence. Tricky: the subsequence does not need to be contiguous.

You can skip elements to maintain the alternating pattern. Flat segments (consecutive equal values) do not contribute to the wiggle because their difference is zero. The longest wiggle is the count of direction changes plus one.