Non-monotonicity
Time limit10sMemory limit128 MB
Given a permutation of 1 to n, find the longest subsequence whose elements alternate down, up, down, starting with a decrease.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Array, Binary search, Greedy
- Solved
- No attempts yet
Problem
There is a sequence of length made up of the distinct integers from to . Among the subsequences of , we want to find the length of the longest sequence that satisfies the following condition.
That is, reading from left to right the elements of must alternately satisfy 'greater than, less than, greater than, less than', and the very first comparison must be 'greater than' (). A subsequence is what remains after deleting zero or more elements from the original sequence, keeping the order of the remaining elements unchanged. A sequence consisting of a single element is also considered to satisfy the condition.
Given , write a program that prints the maximum possible length of .
Input
The first line contains the number of test cases ().
Each test case is given on a single line in the following format.
n A[0] A[1] A[2] ... A[n-1]
Here is the length of the sequence (), followed by the elements of separated by spaces. is a permutation containing each integer from to exactly once.
Output
For each test case, print the maximum length of on its own line.