Wiggle Subsequence

A wiggle sequence is one where the differences between consecutive numbers strictly alternate between positive and negative. The first difference may be either positive or negative. A sequence with one element, or two unequal elements, is trivially a wiggle sequence. For example, `[1, 7, 4, 9, 2, 5]` is a wiggle sequence because its differences `(6, -3, 5, -7, 3)` alternate in sign. `[1, 4, 7, 2, 5]` is not (the first two differences are both positive), and neither is `[1, 7, 4, 5, 5]` (the last difference is zero). A subsequence is obtained by deleting some elements (possibly none) from the original sequence while keeping the rest in order. Given an integer array `nums`, return the length of the longest wiggle subsequence of `nums`.

30:00

Wiggle Subsequence
medium
Free written solution
Topics
Companies

A wiggle sequence is one where the differences between consecutive numbers strictly alternate between positive and negative. The first difference may be either positive or negative. A sequence with one element, or two unequal elements, is trivially a wiggle sequence.

For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because its differences (6, -3, 5, -7, 3) alternate in sign. [1, 4, 7, 2, 5] is not (the first two differences are both positive), and neither is [1, 7, 4, 5, 5] (the last difference is zero).

A subsequence is obtained by deleting some elements (possibly none) from the original sequence while keeping the rest in order.

Given an integer array nums, return the length of the longest wiggle subsequence of nums.

Example 1:
Input: {"nums":[1,7,4,9,2,5]}
Output: 6
Constraints:
  • 1≤nums.length≤10001 \leq \text{nums.length} \leq 1000

  • 0≤nums[i]≤10000 \leq \text{nums}[i] \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,7,4,9,2,5]}

Start with up = down = 1: the single element nums[0] = 1 is a wiggle of length 1, and it can be followed by either a rise or a fall.

nums

── one longest wiggle (1)

107142932455

green points are the turning points kept so far; a run in the same direction just slides its peak or valley forward (dashed amber ring)

up

1

longest wiggle whose last step rises

down

1

longest wiggle whose last step falls

best so far = 1

Variables
VariableValue
up1
down1
DepthFunction Call
Stack empty
0/7