Subsequence Reversal
Time limit2sMemory limit512 MB
Reverse one subsequence of a length-N array, then find the longest non-decreasing subsequence length achievable.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Array, Two pointers, Greedy
- Solved
- No attempts yet
Problem
Farmer John is arranging his cows in a line to take a photo (). The height of the -th cow in the line is . Farmer John thinks the photo will look good if the lineup has a long increasing subsequence of cows by height.
A subsequence is a selection of elements at indices . The subsequence is increasing if .
To make the increasing subsequence long, Farmer John may first choose any one subsequence and reverse the order of its elements.
For example, take the list
1 6 2 3 4 3 5 3 4
Reversing the marked elements
1 6 2 3 4 3 5 3 4
^ ^ ^ ^
gives
1 4 2 3 4 3 3 5 6
^ ^ ^ ^
The reversed subsequence keeps the indices it originally occupied, and every other element stays unchanged.
Find the maximum possible length of an increasing subsequence, given that you may reverse one arbitrary subsequence once.
Input
The first line contains . Each of the next lines contains one of in order. Every value is an integer from to .
Output
Print the maximum length of an increasing subsequence obtainable after reversing at most one subsequence. Reversing nothing is allowed.