Longest Alternating SubsequenceMedium

Longest Alternating Subsequence

MediumPractice library · +20 XPdynamic programminggreedy

Given a sequence of N integers, find the length of the longest subsequence such that the elements alternate in strictly increasing and decreasing order. That is, for a subsequence a[i_1], a[i_2], ..., a[i_k], we must have a[i_1] < a[i_2] > a[i_3] < a[i_4] > ... or a[i_1] > a[i_2] < a[i_3] > a[i_4] < ....

A subsequence is formed by deleting zero or more elements from the original sequence without changing the order of the remaining elements.

Input

The first line contains an integer N, the size of the sequence. The second line contains N space-separated integers representing the sequence.

Output

Print a single integer, the length of the longest alternating subsequence.

Constraints

1 <= N <= 200000 -10^9 <= a[i] <= 10^9

Time limit 1 s (native code; slower languages get more)Memory 256 MB16 hidden tests

Example 1

Input
5
1 5 2 8 3
Output
5

The longest alternating subsequence is 1, 5, 2, 8, 3 itself, with length 5.

Example 2

Input
7
10 20 15 25 30 20 10
Output
5

The longest alternating subsequences include 10, 20, 15, 30, 10 (length 5) or 10, 20, 15, 25, 20, 10 (length 6). The latter is longer.

Hints