This page is still under construction.

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

Warp Points

Time limit2sMemory limit512 MB

Summary
Partition the stars into consecutive blocks; each block's cost is the sum of absolute deviations from its median, and the total cost must be minimized.
Level

Medium7 of 10

Topics
Dynamic programming, Divide and conquer, Prefix sum, Math
Solved
No attempts yet

Problem

You are building an interstellar transportation network. There are NN stars in your region, and your task is to make it possible to travel from any star to any other star. Right now all the stars are isolated, so no star can reach any other star.

As a designer of the interstellar transportation network, you can set warp points. The stars are numbered from 11 to NN, and a warp point lets you come and go between stars with consecutive numbers. The construction cost of a warp point depends on the "potentials" of the stars and of the warp point. The potential of the ii-th star is given as an integer, and you can set the potential of the warp point to any integer. The cost is the sum of the absolute differences between the warp point's potential and the potential of each star it contains.

You can construct any number of warp points. Compute the minimum total cost to make it possible to travel between any pair of stars using some warp points.

For sample input 1, the best plan is to construct one warp point with potential 2.

For sample input 2, three warp points are needed to minimize the total cost. The first warp point connects the first star through the fourth star. The second warp point connects the fourth star through the sixth star. The third warp point connects the sixth star through the tenth star.

Input

The input consists of a single test case in the following format.

NN

a1a_1 …\dots aNa_N

NN is the number of stars (1≤N≤3,0001 \le N \le 3,000). The values a1a_1 through aNa_N are the potentials of the stars. Each potential is guaranteed to be an integer between −1,000,000,000-1,000,000,000 and 1,000,000,0001,000,000,000.

Output

Output the minimum total cost to connect all the stars.

Examples2

  1. Example 1

    Input
    3
    2 5 2
    
    Expected output
    3
    
  2. Example 2

    Input
    10
    1 2 3 2 1 10 9 8 9 10
    
    Expected output
    14