#P7421. 「PMOI-2」子序列

「PMOI-2」子序列

Background

When you see this time limit, there is no need to panic. This problem does not rely on constant-factor tricks.

Problem Description

You are given a sequence aia_i of length nn (indices start from 11). You need to choose a non-empty subsequence pp of {1,2,3,,n}\{1,2,3,\cdots,n\} with any length. Let the length of pp be ll. Define a0=p(0)=an+1=0,p(l+1)=n+1a_0=p(0)=a_{n+1}=0,p(l+1)=n+1. You need to maximize:

$$\sum_{i=0}^{l}(a_{p(i+1)}-a_{p(i)})(p(l-i+1)-p(l-i))$$

Output the maximum value.

If aa is a subsequence of bb, then aa can be obtained by deleting zero or more elements from bb while keeping the original order. For example, {1,4}\{1,4\} is a subsequence of {1,2,3,4}\{1,2,3,4\}, {3,1,5}\{3,1,5\} is a subsequence of {3,1,5}\{3,1,5\}, and {1,2}\{1,2\} is not a subsequence of {3,2,1}\{3,2,1\}.

Input Format

The first line contains a positive integer nn, representing the length of aa.

The second line contains nn integers, where the ii-th number is aia_i.

Output Format

Output one integer, representing the maximum value of $\sum_{i=0}^{l}(a_{p(i+1)}-a_{p(i)})(p(l-i+1)-p(l-i))$.

3
1 5 2
2
5
-2 3 2 5 3
15

Hint

[Sample Explanation]

For the first sample, choosing {1}\{1\} gives the maximum result (10)×(41)+(01)×(10)=2(1-0)\times(4-1)+(0-1)\times(1-0)=2.

For the second sample, choosing {1,5}\{1,5\} gives the maximum result $(-2-0)\times(6-5)+[3-(-2)]\times(5-1)+(0-3)\times(1-0)=15$.

[Constraints]

For 20%20\% of the testdata, n20n\le20 and 0ai1030\le a_i\le10^3.

For 50%50\% of the testdata, n80n\le80.

For 100%100\% of the testdata, 1n3001\le n\le300 and 109ai109-10^9\le a_i\le10^9.

Translated by ChatGPT 5