Under construction

Still being built. Things may change

Make a Monotone Sequence

Time limit2sMemory limit128 MB

Summary
Given N nonnegative integers, build a monotone (non-decreasing or non-increasing) sequence minimizing the total absolute difference from the original.
Level

Hard8 of 10

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

Problem

You are given a sequence A1,A2,…,ANA_1, A_2, \dots, A_N of NN nonnegative integers. Choose a sequence B1,B2,…,BNB_1, B_2, \dots, B_N to minimize ∣A1−B1∣+∣A2−B2∣+⋯+∣AN−BN∣|A_1-B_1| + |A_2-B_2| + \dots + |A_N-B_N|.

The sequence BB must be monotone. That means it must satisfy either B1≤B2≤⋯≤BNB_1 \le B_2 \le \dots \le B_N or B1≥B2≥⋯≥BNB_1 \ge B_2 \ge \dots \ge B_N.

Input

The first line contains the length NN of the sequence. Each of the next NN lines contains one value of A1,A2,…,ANA_1, A_2, \dots, A_N in order.

Output

Print the minimum possible sum of absolute differences.

Constraints

  • 1≤N≤2 0001 \le N \le 2\,000
  • 0≤Ai≤1 000 000 0000 \le A_i \le 1\,000\,000\,000

Examples1

  1. Example 1

    Input
    7
    1
    3
    2
    4
    5
    3
    9
    
    Expected output
    3