cswork / OAOpen practice workspace

AmazonOA #350

Sum of Max of Subarrays

Estimated HardJudge-ready

Topics (AI-labelled)Stacks & HeapsBits & Math

Every non-empty contiguous subarray contributes its maximum multiplied by its length; find the sum of all contributions. Negative numbers are allowed, and the answer must be output exactly, without any modulus; a linear-time algorithm is required.

Input

The first line contains n and the second line contains n integers. On this site 0≤n≤200000 and elements are in −10^9..10^9.

Output

Output a single integer, the answer.

Example 1

Input:

4
4 2 1 2

Output:

59

Example 2

Input:

3
-3 -1 -1

Output:

-12

Example 3

Input:

0

Output:

0

Example notes

The outputs of the three public examples are 59; -12; and 0, checked by independent enumeration or direct simulation.

Editorial

Loading solution…