All problems

Problem 758

Longest Bitonic Subsequence

Medium · 20 pts · Dynamic Programming, Array

Problem

A sequence is bitonic if it first strictly increases and then strictly decreases. Either part may be empty, so a strictly increasing or strictly decreasing sequence also counts, and so does a single element. Find the length of the longest bitonic subsequence of the array. Compute the longest strictly increasing subsequence ending at each index (from the left) and the longest strictly decreasing one starting at each index (from the right); the answer is the best sum of the two minus one.

Input

The first line contains N. The second line contains N integers.

Output

Print the length of the longest bitonic subsequence.

Constraints

1 <= N <= 1000; 1 <= A[i] <= 10^5

Example input

8
1 11 2 10 4 5 2 1

Example output

6

Explanation

In 1 11 2 10 4 5 2 1, the subsequence 1 2 10 4 2 1 rises to 10 and then falls. It has 6 elements, and no longer bitonic subsequence exists.

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

Previous: Print Longest Common Subsequence Next: Subtract Two Numbers