This page is still under construction.

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

Spreading Out the Cows

Interview

Time limit1sMemory limit128 MB

Summary
Place N cows into S stalls so adjacent gaps are D or D+1 with as many D as possible, minimizing total movement from given start positions.
Level

Medium7 of 10

Topics
Dynamic programming, Greedy, Sorting, Math
Solved
No attempts yet

Problem

Farmer John keeps NN prize milk cows numbered 11 through NN. His freshly painted barn has SS stalls numbered 11 through SS laid out in a single line, and every pair of neighboring stalls is exactly 11 unit of distance apart.

The cows have settled into the stalls to rest: cow ii is in stall PiP_i. Because the cows are antisocial and get grumpy when packed too close together, Farmer John wants to move them so they are as spread out as possible.

He wants the N−1N-1 distances between adjacent cows to be as large as possible and also as uniform as possible (close to equal spacing). Concretely, let D=⌊(S−1)/(N−1)⌋D = \lfloor (S-1)/(N-1) \rfloor using integer division. Every distance between adjacent cows must differ from DD by at most 11, and as many of those distances as possible must equal exactly DD.

For instance, with four cows and eight stalls the cows may be placed at 1,3,5,81, 3, 5, 8 or 1,3,6,81, 3, 6, 8, but not at 1,2,4,71, 2, 4, 7 or 1,2,4,81, 2, 4, 8.

Compute the minimum total distance the cows must move to achieve such a spacing. Ignore the distance a cow needs to enter or leave a stall.

Input

  • Line 1: two space-separated integers NN and SS.
  • Lines 2 through N+1N+1: line i+1i+1 contains a single integer PiP_i.

Constraints: 2≤N≤15002 \le N \le 1500, N≤S≤1000000N \le S \le 1000000, 1≤Pi≤S1 \le P_i \le S.

Output

  • A single integer: the minimum total distance the cows must travel. This value is guaranteed to be under 1,000,000,000, so it fits comfortably in a signed 32-bit integer.

Hint

The diagram below illustrates a barn with 55 cows and 1010 stalls whose starting positions are 1,2,3,8,91, 2, 3, 8, 9.

               1   2   3   4   5   6   7   8   9  10
Cow Locs     | A | B | C | . | . | . | . | D | E | . |

Cows move from stall 22 to 33, from 33 to 55, and from 99 to 1010. The total distance moved is 1+2+1=41 + 2 + 1 = 4. The final positions of the cows are stalls 1,3,5,8,101, 3, 5, 8, 10.

                 1   2   3   4   5   6   7   8   9  10
Init Stall     | A | B | C | . | . | . | . | D | E | . |
Final Stall    | A | . | B | . | C | . | . | D | . | E |
Distance moved | 0 | . | 1 | . | 2 | . | . | 0 | . | 1 |

Examples1

  1. Example 1

    Input
    5 10
    2
    8
    1
    3
    9
    
    Expected output
    4