Payback
Time limit1sMemory limit128 MB
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 () friends, conveniently labeled .
Payback day has finally come. In total Bessie is owed more money than she owes. The friends stand in a straight line, friend standing meters from the barn. Bessie starts at the barn (position ) and walks along the line, collecting money from those who owe her and repaying those she owes.
Each friend has an integer (, ): if , friend owes Bessie ; if , Bessie owes friend the amount .
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 ) and must finish at the far end of the line (position ). What is the minimum total distance she must travel to settle every account?
Input
- Line 1: A single integer .
- Lines 2 to : Line contains a single integer .
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 to with values .
- From the barn Bessie walks right and collects from friend (she now holds ).
- Friend is owed , but Bessie holds only , so she walks past and continues to friend , collecting (she now holds ).
- She walks back to friend and repays (she now holds ).
- She walks right again to friend , passing friend (owed , but she holds only ) and collecting from friend (she now holds ).
- She walks back to friend and repays (she now holds ), then returns to the end of the line, where her journey ends.
The distances are .