This page is still under construction.

Parts of this page are still being built. What you see may change.

Insulator

Interview

Time limit1sMemory limit128 MB

Summary
Given n positive coefficients, reorder them so that the sum plus the total of positive rises between adjacent layers is as large as possible, and print that maximum.
Level

Medium5 of 10

Topics
Greedy, Sorting, Math, Array
Solved
No attempts yet

Problem

The company Insumax produces multi-layer thermal insulators. Each insulator consists of nn layers, and the ii-th layer (i=1,2,…,ni = 1, 2, \dots, n) is described by a positive integer insulation coefficient aia_i. The layers are numbered along the direction in which heat leaks out.

heat  ->  || a1 | a2 | ... | ai | ai+1 | ... | an ||  ->

The insulation coefficient AA of the whole insulator is the sum of the coefficients of its layers. In addition, whenever a layer is followed by a layer with a larger coefficient, AA grows by that difference. Formally,

A=∑i=1nai+∑i=1n−1max⁡(0, ai+1−ai)A = \sum_{i=1}^{n} a_i + \sum_{i=1}^{n-1} \max(0,\ a_{i+1} - a_i)

For example, arranging the layers in the order 5,4,1,75, 4, 1, 7 gives A=(5+4+1+7)+(7−1)=23A = (5 + 4 + 1 + 7) + (7 - 1) = 23.

Given the coefficients a1,a2,…,ana_1, a_2, \dots, a_n of the layers, arrange them so that the total insulation coefficient AA is maximized, and output that maximum value.

Input

The first line contains the number of layers nn (1≤n≤1000001 \le n \le 100000). Each of the next nn lines contains one coefficient aia_i. Every coefficient is an integer satisfying 1≤ai≤100001 \le a_i \le 10000.

Output

Output a single integer: the largest possible value of the total insulation coefficient AA over all orderings of the layers.

Examples3

  1. Example 1

    Input
    4
    5
    4
    1
    7
    
    Expected output
    24
    
  2. Example 2

    Input
    2
    1
    10000
    
    Expected output
    20000
    
  3. Example 3

    Input
    3
    5
    5
    5
    
    Expected output
    15