All problems

Problem 472

Wiggle Subsequence

Medium · 20 pts · Array, Greedy, Dynamic Programming

Problem

A wiggle sequence is one where the differences between consecutive elements strictly alternate between positive and negative, such as 1 7 4 9 2 5 (up, down, up, down, up). A single element is a wiggle sequence of length 1, and two different elements form one of length 2. Equal neighbours (a difference of 0) are never allowed. Find the length of the longest wiggle subsequence of the array. Greedily counting the turning points of the array gives the answer in O(N).

Input

First line: N. Second line: N integers.

Output

Print the length of the longest wiggle subsequence.

Constraints

1 <= N <= 1000; 0 <= A[i] <= 1000

Example input

6
1 7 4 9 2 5

Example output

6

Explanation

The whole array 1 7 4 9 2 5 already alternates: up 6, down 3, up 5, down 7, up 3. So the answer is 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Moves to Equal Array Elements Next: Maximum Swap