Problem:
Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0

Solution in Ruby (2.3.3) (judge verdict: Runtime Error)

# frozen_string_literal: true

INFINITY = 10000000
$min = INFINITY
$mem_dfs = {}
$n, $m = gets.split.map(&:to_i)
x = gets.split.map(&:to_i)

if $n >= $m
  puts 0
  exit 0
end

$sorted_x = x.sort

def score(prevpos, pos)
  return 0 if pos - 1 < prevpos

  $sorted_x[pos - 1] - $sorted_x[prevpos]
end

def dfs(i, prevpos, pos, psum)
  return score(prevpos, pos) + score(pos, $m) if i == $n - 1
  return INFINITY if pos >= $m - 1

  sc = score(prevpos, pos)
  return INFINITY if sc > $min
  psum += sc
  #return INFINITY if psum > $min
  a_min = INFINITY
  (pos+1..$m - $n + i + 1).each do |p|
    index = "#{i + 1}_#{pos}_#{p}"
    d = $mem_dfs[index] || dfs(i + 1, pos, p, psum)
    a_min = [d, a_min].min
  end
  s = sc + a_min
  $min = [s, $min].min
  index = "#{i}_#{prevpos}_#{pos}"
  $mem_dfs[index] ||= s
  s
end

puts dfs(0, 0, 0, 0)