Under construction

Still being built. Things may change

Payback

Time limit1sMemory limit128 MB

Summary
Friends stand at positions 1 to N with signed debts; Bessie starts at 0 holding nothing, must never go negative, and finishes at N. Find the minimum walking distance to settle all accounts.
Level

Hard8 of 10

Topics
Greedy, Array, Prefix sum
Solved
No attempts yet

Problem

Bessie has borrowed money from, or lent money to, each of her NN (1≤N≤1000001 \le N \le 100000) friends, conveniently labeled 1…N1 \dots N.

Payback day has finally come. In total Bessie is owed more money than she owes. The friends stand in a straight line, friend ii standing ii meters from the barn. Bessie starts at the barn (position 00) and walks along the line, collecting money from those who owe her and repaying those she owes.

Each friend ii has an integer DiD_i (−1000≤Di≤1000-1000 \le D_i \le 1000, Di≠0D_i \ne 0): if Di>0D_i > 0, friend ii owes Bessie DiD_i; if Di<0D_i < 0, Bessie owes friend ii the amount ∣Di∣|D_i|.

When Bessie passes a friend who owes her, she may collect that money at once. She may repay a friend she owes only while she is currently holding at least that amount of cash (the cash she holds can never become negative). Because she may not have enough cash when she first reaches a friend she owes, she may have to walk past that friend, collect more money farther down the line, and come back to repay later.

Bessie starts at the barn (position 00) and must finish at the far end of the line (position NN). What is the minimum total distance she must travel to settle every account?

Input

  • Line 1: A single integer NN.
  • Lines 2 to N+1N+1: Line i+1i+1 contains a single integer DiD_i.

Output

  • Line 1: A single integer — the minimum total distance Bessie must travel to collect from and repay every friend.

Hint

In the sample, the five friends stand at positions 11 to 55 with values 100,−200,250,−200,200100, -200, 250, -200, 200.

  • From the barn Bessie walks right and collects 100100 from friend 11 (she now holds 100100).
  • Friend 22 is owed 200200, but Bessie holds only 100100, so she walks past and continues to friend 33, collecting 250250 (she now holds 350350).
  • She walks back to friend 22 and repays 200200 (she now holds 150150).
  • She walks right again to friend 55, passing friend 44 (owed 200200, but she holds only 150150) and collecting 200200 from friend 55 (she now holds 350350).
  • She walks back to friend 44 and repays 200200 (she now holds 150150), then returns to the end of the line, where her journey ends.

The distances are 3+1+3+1+1=93 + 1 + 3 + 1 + 1 = 9.

Examples3

  1. Example 1

    Input
    5
    100
    -200
    250
    -200
    200
    
    Expected output
    9
    
  2. Example 2

    Input
    1
    5
    
    Expected output
    1
    
  3. Example 3

    Input
    2
    -500
    1000
    
    Expected output
    4