Under construction

Still being built. Things may change

Reducing a Sequence

Time limit1sMemory limit128 MB

Summary
Given a sequence, find the minimum total cost of repeatedly merging adjacent elements where cost equals the max of the pair, until one element remains.
Level

Medium4 of 10

Topics
Greedy, Array
Solved
No attempts yet

Problem

You are given a sequence a1,a2,…,ana_1, a_2, \dots, a_n. The operation reduce(i)\text{reduce}(i) merges the two adjacent elements aia_i and ai+1a_{i+1} into a single element and places max⁡(ai,ai+1)\max(a_i, a_{i+1}) in their position. Each time this operation is performed, the length of the sequence decreases by 11.

The cost of one reduce\text{reduce} operation is the maximum of the two merged elements, max⁡(ai,ai+1)\max(a_i, a_{i+1}). Performing the operation n−1n-1 times on a sequence of length nn reduces its length to 11.

Compute the minimum possible sum of the costs of all reduce\text{reduce} operations needed to reduce the sequence to length 11.

Input

The first line contains the length of the sequence nn (1≤n≤1,000,000)(1 \le n \le 1{,}000{,}000). Each of the next nn lines contains one element aia_i of the sequence in order (0≤ai≤1,000,000,000)(0 \le a_i \le 1{,}000{,}000{,}000).

Output

Print the minimum sum of costs required to reduce the sequence to length 11.

Examples5

  1. Example 1

    Input
    3
    1
    2
    3
    
    Expected output
    5
    
  2. Example 2

    Input
    1
    7
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    10
    3
    
    Expected output
    10
    
  4. Example 4

    Input
    3
    3
    2
    1
    
    Expected output
    5
    
  5. Example 5

    Input
    3
    2
    1
    3
    
    Expected output
    5