This page is still under construction.

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

Flatten

Interview

Time limit1sMemory limit128 MB

Summary
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

NN piles of chips are placed in a row, and each pile contains zero or more chips. The piles are numbered 11 through NN from left to right.

In one move you pick a pile pp and an integer mm, then transfer mm chips from pile pp to each of its neighboring piles.

  • If 1<p<N1 < p < N, pile pp has two neighbors, p−1p-1 and p+1p+1.
  • If p=1p = 1, its only neighbor is pile 22.
  • If p=Np = N, its only neighbor is pile N−1N-1.

To perform a move, a pile with two neighbors must hold at least 2m2m chips (it sends mm to each side), and a pile with only one neighbor must hold at least mm 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 2m2m chips when the chosen pile has two neighbors, and mm chips when it has only one neighbor. Determine the minimum total number of chips that must be transferred to flatten all piles.

Figure 1. Five piles with 0, 7, 8, 1 and 4 chips.Figure 2. The same piles after the move p=2p=2, m=2m=2.

Input

  • The first line contains the number of piles NN.
  • The second line contains NN integers; the ii-th of them is CiC_i, the number of chips in pile ii.

Output

  • Print a single integer: the minimum total number of chips that must be transferred to flatten all piles.

Constraints

  • 2≤N≤2002 \le N \le 200
  • 0≤Ci≤20000 \le C_i \le 2000, where CiC_i is the number of chips in pile ii at the start (1≤i≤N1 \le i \le N).
  • The total number of chips is a multiple of NN, and it is guaranteed that the piles can always be flattened.

Examples3

  1. Example 1

    Input
    5
    0 7 8 1 4
    
    Expected output
    24
    
  2. Example 2

    Input
    2
    0 4
    
    Expected output
    2
    
  3. Example 3

    Input
    3
    3 0 3
    
    Expected output
    2