Under construction

Still being built. Things may change

Container Rearrangement

Interview

Time limit1sMemory limit1024 MB

Summary
Given container counts in n slots, find the fewest containers to move so that every pair of slots differs in height by at most 1.
Level

Medium4 of 10

Topics
Greedy, Sorting
Solved
No attempts yet

Problem

A yard at a port has nn slots in a row on its floor where containers can be stacked, and the yard currently holds mm containers. Every container has height 1, and there is no limit on how many containers a slot can hold. If aia_i (1≤i≤n1 ≤ i ≤ n) is the number of containers stacked in the ii-th slot, then m=∑i=1naim = \sum_{i=1}^{n} a_i holds.

With no height limit, the counts in each slot can differ greatly, which can cause safety problems. So a crane moves some containers to other slots so that the height difference between any two slots is at most 1. That is, ∣ai−aj∣≤1|a_i - a_j| ≤ 1 must hold for any ii and jj. Containers can be moved only one at a time, and moving a container has no extra cost based on distance.

For example, in Figure 1, 35 containers are stacked in 8 slots, so m=35m = 35 and n=8n = 8. Rearranging them so that the height difference is at most 1 gives the result in Figure 2, and 5 containers must be moved.

Figure 1. Before rearrangementFigure 2. Result of rearrangement

Input

The first line contains a positive integer nn (1≤n≤1061 ≤ n ≤ 10^6), the number of slots. The next line contains nn non-negative integers a1,a2,…,ana_1, a_2, \dots, a_n, the number of containers currently in each slot. The total number of containers mm satisfies 1≤m≤2×1091 ≤ m ≤ 2 \times 10^9.

Output

Print, on one line, the minimum number of containers that must be moved to satisfy the condition.

Examples2

  1. Example 1

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

    Input
    8
    5 6 7 2 3 4 2 6
    
    Expected output
    5