This page is still under construction.

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

Banks

Time limit5sMemory limit256 MB

Summary
Flipping a negative bank in a circle to positive takes the same amount from both neighbors; the goal is the fewest flips leaving every capital nonnegative.
Level

Medium7 of 10

Topics
Greedy, Simulation, Math
Solved
No attempts yet

Problem

Wall Street in Wonderland has nn banks standing in a circle, so every bank has one left neighbour and one right neighbour. The left neighbour of the first bank is the last bank, and the right neighbour of the last bank is the first bank. The banks are numbered from 00 to n−1n-1. The left neighbour of bank ii is bank (i−1+n) mod n(i-1+n) \bmod n and its right neighbour is bank (i+1) mod n(i+1) \bmod n.

Bank ii has capital kik_i. The capitals of all banks add up to a positive number.

Whenever the capital kik_i of some bank ii is negative, the Bank Fairy spends one magic move and turns that capital into a positive one. If ki=−7k_i = -7, then ki=7k_i = 7 after the magic move. Both neighbours pay for it: the capital of the left neighbour and the capital of the right neighbour each drop by ∣ki∣|k_i|. If the left neighbour held 55 and the right neighbour held 1111, they hold −2-2 and 44 after the move.

The drop applies once per neighbour relation. When n=2n = 2 the remaining bank is both the left and the right neighbour, so its capital drops by 2∣ki∣2|k_i|. When n=1n = 1 the only capital is positive, so no magic move is ever possible.

What is the minimal number of magic moves the Bank Fairy has to make so that the capital of every bank is greater than or equal to 00?

Input

The first line contains the number of banks nn (0<n<100000 < n < 10000).

The second line contains the capitals k0,k1,…,kn−1k_0, k_1, \dots, k_{n-1} in the order in which the banks stand on Wall Street, separated by single spaces. Each capital is an integer with −32000<ki<32000-32000 < k_i < 32000, and their sum is positive.

Output

Print the minimal number of magic moves on a single line.

Examples4

  1. Example 1

    Input
    4
    1 -2 -1 3
    
    Expected output
    9
    
  2. Example 2

    Input
    1
    7
    
    Expected output
    0
    
  3. Example 3

    Input
    2
    -3 10
    
    Expected output
    1
    
  4. Example 4

    Input
    5
    0 0 0 0 2
    
    Expected output
    0