Subarray Cost

시간 제한5초메모리 제한2048 MB

요약
길이가 2 이상인 부분 배열 중에서 (길이) 곱하기 (가장 작은 두 원소의 합)을 최대로 만드는 값을 구한다.
난이도

어려움10점 중 8점

유형
스택, 분할 정복, 배열, 그리디
정답자
아직 제출이 없습니다

문제

Given an array AA of length NN, a subarray A\[l…r]A\[l \ldots r] is defined as the part of the array AA that includes only the elements located at positions from ll to rr inclusively. The cost of a subarray is defined as the product of the length of the subarray and the sum of its two smallest elements.

For example, let the array be A=\[5,1,3,5,3]A = \[5, 1, 3, 5, 3]. Let us consider the subarray A\[2…4]=\[1,3,5]A\[2 \ldots 4] = \[1, 3, 5]. Its length is 33, its smallest element is 11, and its second smallest element is 33. Therefore, its cost is 3⋅(1+3)=123 \cdot (1 + 3) = 12. Let us consider another subarray, A\[1…2]=\[5,1]A\[1 \ldots 2] = \[5, 1]. Its length is 22, its smallest element is 11, and its second smallest element is 55. Therefore, its cost is 2⋅(1+5)=122 \cdot (1 + 5) = 12.

Note that if the minimal value occurs more than once in a subarray, it is counted several times. For example, the length of the subarray A\[3…5]=\[3,5,3]A\[3 \ldots 5] = \[3, 5, 3] is 33, its smallest element is 33, and its second smallest element is also 33. Therefore, its cost is 3⋅(3+3)=183 \cdot (3 + 3) = 18.

Given an array, find the maximum cost over all subarrays of at least two elements. That is, you need to find the maximum cost over all subarrays A\[l…r]A\[l \ldots r], where 1≤l<r≤N1 \le l < r \le N.

입력

The first line contains NN (2≤N≤1062 \le N \le 10^6), the length of the array. The second line contains NN integers A_1,A_2,…,A_NA\_1, A\_2, \dots, A\_N (1≤A_i≤1091 \le A\_i \le 10^9).

출력

Output a single integer, the maximum cost over all subarrays of at least two elements.

예제3

  1. 예제 1

    입력
    5
    5 1 3 5 3
    
    예상 출력
    20
    
  2. 예제 2

    입력
    7
    1 1 3 5 10 77 5
    
    예상 출력
    174
    
  3. 예제 3

    입력
    3
    1 2 3
    
    예상 출력
    10