Subsequence Reversal

Reverse one subsequence of a length-N array, then find the longest non-decreasing subsequence length achievable.

Hard8Dynamic programmingArrayTwo pointersGreedyNo attempts yetTime limit2sMemory limit512 MB

Problem

Farmer John is arranging his NN cows in a line to take a photo (1N501 \le N \le 50). The height of the ii-th cow in the line is a(i)a(i). 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 a(i1),a(i2),,a(ik)a(i_1), a(i_2), \ldots, a(i_k) at indices i1<i2<<iki_1 < i_2 < \cdots < i_k. The subsequence is increasing if a(i1)a(i2)a(ik)a(i_1) \le a(i_2) \le \cdots \le a(i_k).

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 NN. Each of the next NN lines contains one of a(1),,a(N)a(1), \ldots, a(N) in order. Every value is an integer from 11 to 5050.

Output

Print the maximum length of an increasing subsequence obtainable after reversing at most one subsequence. Reversing nothing is allowed.