Flatten
InterviewTime limit1sMemory limit128 MB
Distribute chips between neighboring piles at a cost equal to the chips moved, and find the minimum total transferred to make all piles equal.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Greedy, Math, Prefix sum
- Solved
- No attempts yet
Problem
piles of chips are placed in a row, and each pile contains zero or more chips. The piles are numbered through from left to right.
In one move you pick a pile and an integer , then transfer chips from pile to each of its neighboring piles.
- If , pile has two neighbors, and .
- If , its only neighbor is pile .
- If , its only neighbor is pile .
To perform a move, a pile with two neighbors must hold at least chips (it sends to each side), and a pile with only one neighbor must hold at least chips.
By repeating such moves, the goal is to flatten the piles, that is, to make every pile hold the same number of chips.
A single move transfers chips when the chosen pile has two neighbors, and chips when it has only one neighbor. Determine the minimum total number of chips that must be transferred to flatten all piles.
Input
- The first line contains the number of piles .
- The second line contains integers; the -th of them is , the number of chips in pile .
Output
- Print a single integer: the minimum total number of chips that must be transferred to flatten all piles.
Constraints
- , where is the number of chips in pile at the start ().
- The total number of chips is a multiple of , and it is guaranteed that the piles can always be flattened.

