Estimation

Time limit5sMemory limit128 MB

Summary
Partition an array into k contiguous sections, each replaced by one constant value, to minimize the total absolute error. Multiple test cases until 0 0.
Level

Medium7 of 10

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

Problem

"There are too many numbers here!" your boss bellows. "How am I supposed to make sense of all of this? Pare it down! Estimate!"

You are disappointed, because it took a lot of work to generate those numbers, but you will do what your boss asks.

You decide to estimate as follows. You are given an array AA of nn numbers, and you partition it into kk contiguous sections that need not have the same size. Each section is then estimated by a single number. Formally, from the array AA of size nn you build another array BB of size nn that consists of kk contiguous sections: whenever indices ii and jj lie in the same section, B[i]=B[j]B[i] = B[j]. Your goal is to minimize the error, defined as the sum of the absolute differences ∑∣A[i]−B[i]∣\sum |A[i] - B[i]|.

Input

The input contains several test cases. Each test case starts with a line holding two integers nn (1≤n≤20001 \le n \le 2000) and kk (1≤k≤251 \le k \le 25 and k≤nk \le n), where nn is the size of the array and kk is the number of contiguous sections to use. Each of the next nn lines contains one integer of AA; every element satisfies −10000≤A[i]≤10000-10000 \le A[i] \le 10000. The input ends with a line containing two zeros.

Output

For each test case, output a single line containing one integer: the minimum error you can achieve. Print no extra spaces, and do not separate answers with blank lines. Every answer fits in a signed 64-bit integer.

Examples4

  1. Example 1

    Input
    7 2
    6
    5
    4
    3
    2
    1
    7
    0 0
    
    Expected output
    9
    
  2. Example 2

    Input
    5 1
    1
    2
    3
    4
    5
    0 0
    
    Expected output
    6
    
  3. Example 3

    Input
    4 4
    10
    -10
    5
    3
    0 0
    
    Expected output
    0
    
  4. Example 4

    Input
    1 1
    5
    0 0
    
    Expected output
    0