This page is still under construction.

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

The Running Game

Time limit1sMemory limit512 MB

Summary
Pick disjoint segments of the given sequence so the sum of each segment weighted by its position inside the segment is as large as possible.
Level

Medium7 of 10

Topics
Dynamic programming, Prefix sum, Segment tree
Solved
No attempts yet

Problem

A game where you run along a straight line and eat scored objects one after another is popular right now. Kyungkeun, who picks up trends a little late, made one of these games too. It has no name yet.

The game has a multiplier that is applied to the score of every object the character eats. The multiplier is 0 when the game starts. The character starts from a point far to the left and runs to the right, meeting the objects Kyungkeun placed on the line in order. When the character eats an object, the multiplier first increases by 1, and then (score of the eaten object) ×\times (the increased multiplier) is added to the score the character has collected. When the character does not eat an object, the multiplier resets to 0 and no score is gained. An object's score is not guaranteed to be positive, so a high score requires choosing carefully which objects to eat and which to pass. Once that is decided the character runs on to the right, and it can never go back to the left.

On Kyungkeun's map the character meets NN objects in order. Given the scores of the objects in the order they are placed, find the largest score the character can collect.

Input

The first line contains a natural number NN (1≤N≤1061 \le N \le 10^6).

The second line contains NN integers separated by spaces, the scores of the objects. They are given in the order the objects are placed on the map, so the character meets them in that order. The absolute value of each integer is at most 10610^6.

Output

Print the largest score the character can collect on the given map. The answer can exceed the range of a 32-bit integer, so use a 64-bit integer type.

Hint

In the first example, eating all three objects is best.

  • Eating only the third object gives 5×1=55 \times 1 = 5 points.
  • Eating the second and the third object gives (−1)×1+5×2=9(-1) \times 1 + 5 \times 2 = 9 points.
  • Eating all three objects gives (−1)×1+(−1)×2+5×3=12(-1) \times 1 + (-1) \times 2 + 5 \times 3 = 12 points.

Examples3

  1. Example 1

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

    Input
    1
    -5
    
    Expected output
    0
    
  3. Example 3

    Input
    3
    5 -100 5
    
    Expected output
    10