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 (Python):
n, m = map(int,input().split())
x = sorted(list( map(int,input().split())))
if n >= m:
    print(0)
else:
    d = [0]*(m-1)
    for i in range(m-1):
        d[i] = x[i+1] - x[i]
    d.sort()
    print(sum(d[0:m-n]))

Solution (Python):
n,m = map(int,input().split())

x = list(map(int,input().split()))

x = sorted(x)

r = [x[i+1] - x[i] for i in range(m-1)]

r = sorted(r,reverse = True)
print(sum(r[n-1:]))

Solution (Python):

n,m = map(int,input().split())

x = list(map(int,input().split()))

x.sort()
cnt = 0
l = [0] * (len(x)-1)

if n < m :
  for i in range(len(x)-1):
    l[i] = x[i+1] - x[i] 
  
  l.sort()
  cnt = l[0:m-n]
  
  print(sum(cnt))
else :
  print(cnt)

Solution (Python):
n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))

if n >= m:
    print(0)
else:
    x = sorted([x[i] - x[i - 1] for i in range(1, m)])
    print(sum(x[:m-n]))

Solution (Python):
n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))

if n >= m:
    print(0)
else:
    ans = x[m-1]-x[0]
    x = sorted([x[i] - x[i - 1] for i in range(1, m)])
    print(ans - sum(x[m-n:]))

Solution (Python):
N,M = [int(x) for x in input().split()]
X = [int(x) for x in input().split()]

X.sort()
diff = []
for i in range(1,len(X)):
    diff.append((X[i] - X[i-1]))

diff.sort()
diff = diff[:M-N]
if(N<M):
    print(sum(diff))
else:
    print("0")

Solution (Python):
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
c=0
l=[]
for i in range(m-1):
    l.append(abs(x[i]-x[i+1]))
l.sort()
if len(l)-n+1<=0:
    print("0")
else:
    for i in range(len(l)-n+1):
        c+=l[i]
    print(c)

Solution (Python):
n,m = map(int,input().split())
x = sorted(list(map(int,input().split())))
dif = []
for i in range(m-1):
    dif.append(x[i+1]-x[i])
dif.sort()
print(sum(dif[:max(m-n,0)]))

Solution (Python):
N,M=map(int, input().split())
X=list(map(int, input().split()))
if N>=M:
    print(0)
    exit()

X=sorted(X)

L=[]
for i in range(len(X)):
    L.append(abs(X[i]-X[i-1]))

print(sum(sorted(L)[:(M-N)]))

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, m = map(int, input().split())
    X = sorted(list(map(int, input().split())))

    dist = []
    for i in range(1, m):
        dist.append(X[i] - X[i - 1])

    dist = sorted(dist, reverse=True)
    res = 0
    for i in range(n - 1, len(dist)):
        res += dist[i]

    print(res)


if __name__ == '__main__':
    resolve()

Solution (Python):
n, m = map(int, input().split())
spots = list(map(int, input().split()))
spots.sort()
diff = []
for i in range(1, m):
    diff.append(abs(spots[i] - spots[i - 1]))
diff.sort(reverse=True)
ans = sum(diff[n - 1:])
print(ans)

Solution (Python):
N, M = map(int, input().split())
X = list(map(int, input().split()))
ans = 0
if M>N:
  X.sort()
  D = []
  for i in range(M-1):
    d = X[i+1]-X[i]
    D.append(d)
  
  D.sort()
  D = D[:(M-N)]
  ans = sum(D)
  
print(ans)

Solution (Python):
n, m = map(int, input().split())
x = list(map(int, input().split()))

x.sort()
d = []
for i in range(m-1):
    d.append(x[i+1] - x[i])

d.sort(reverse=True)


print(sum(d[n-1:]))

Solution (Python):
N,M = map(int,input().split())
A = list(map(int,input().split()))
A.sort()

B = []
for i in range(M-1):
  B.append(abs(A[i+1]-A[i]))
B.sort()



if N >=M:
  ans = 0
if N == 1:
  ans = sum(B)
else:
  ans = sum(B[:-(N-1)])
print(ans)

Solution (Python):
n, m = map(int, input().split())
x = list(map(int, input().split()))
x.sort()

d = []
for i in range(m-1):
    d.append(x[i+1] - x[i])
d.sort(reverse=True)

print((x[-1] - x[0]) - sum(d[:n-1]))

Solution (Python):
N,M = map(int,input().split())

List = list(map(int,input().split()))
List.sort()

sa = []

for i in range(M-1):
  a = List[i+1] - List[i]
  sa.append(a)
  
sa.sort()
l = len(sa)

if N >= M:
  print(0)
else:
  print(sum(sa[:l-N+1]))

Solution (Python):
n,m=map(int, input().split())
x=list(map(int, input().split()))

x=sorted(x)
dis=[0]*(m-1)
for i in range(m-1):
    dis[i]=x[i+1]-x[i]
dis=sorted(dis,reverse=True)[(n-1):]
print(sum(dis))

Solution (Python):
N, M = map(int, input().split())
X = list(map(int, input().split()))

X.sort()
diff = [0]*(M-1)
for i in range(M-1):
    diff[i] = X[i+1]-X[i]

diff.sort()
if N>=M:
    ans = 0
else:
    ans = sum(diff[:M-N])
print(ans)

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    n,m=map(int, input().split())
    l=list(map(int,input().split()))
    l.sort()
    if n==1 and m>=2:
        print(l[-1]-l[0])
    elif n>=m:
        print(0)
    else:
        aida=[]
        for i in range(m-1):
            aida.append(l[i+1]-l[i])
        aida.sort()
        print(sum(aida[:m-n]))
resolve()

Solution (Python):
[N,M] = list(map(int,input().split()))
X = list(map(int,input().split()))
X = sorted(X)


if N>=M:
    out=0
else:
    aida=[0]*(M-1)
    for i in range(M-1):
        aida[i] = X[i+1] - X[i]
    
    aida = sorted(aida, reverse=True)

    out = X[-1] - X[0]
    for j in range(N-1):
        out-=aida[j]

print(out)

Solution (Python):
n,m,*x = map(int,open(0).read().split())
x.sort()
if n >= m:
  print(0)
  exit()
a = sorted([x[i+1]-x[i] for i in range(m-1)],reverse=True)
ans = x[-1]-x[0]
for i in range(n-1):
  ans -= a[i]
print(ans)

Solution (Python):
N, M = map(int, input().split())
X = list(map(int, input().split()))
X = sorted(X)
Y = [0]*(M-1)
for i in range(M-1):
  Y[i] = X[i+1] - X[i]
Y = sorted(Y)
if N == 1:
  print(sum(Y))
else:
  print(sum(Y[:-N+1]))

Solution (Python):
n, m = list(map(int, input().split()))
xxx = list(map(int, input().split()))

if n >= m:
    print(0)
    exit()
xxx.sort()
ddd = [b - a for a, b in zip(xxx, xxx[1:])]
ddd.sort()
print(sum(ddd[:m - n]))

Solution (Python):
N, M = map(int, input().split())
X = list(map(int, input().split()))

X.sort()
L = [X[i+1] - X[i] for i in range(M-1)]
L.sort()
N = M if N > M else N
print(sum(L[:(M-1)-(N-1)]))

Solution (Python):
n,m = map(int,input().split())
li = list(map(int,input().split()))
lia = []
li.sort()
for i in range(m-1):
    lia.append(abs(li[i]-li[i+1]))
lia.sort(reverse=True)
del lia[:n-1]
print(sum(lia))

Solution (Python):
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
ans=[]
for i in range(m-1):
    ans.append(x[i+1]-x[i])
ans.sort()
if n<m:
    print(sum(ans[:m-n]))
else:
    print(0)

Solution (Python):
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
l=[]
for i in range(m-1):
  l.append(x[i+1]-x[i])
l.sort(reverse=True)
cnt=sum(l[:n-1])
print(sum(l)-cnt)

Solution (Python):

N, M = map(int, input().split())
X = list(map(int, input().split()))

X.sort()
K = sorted(
    [
        abs(X[i] - X[i - 1])
        for i in range(1, M)
    ],
    reverse=True
)

print(sum(K[N - 1:]))

Solution (Python):
n,m = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
r = []
for i in range(m-1):
    r.append(x[i+1]-x[i])
r.sort(reverse=True)
print(sum(r[n-1:]))

Solution (Python):
[N,M] = list(map(int,input().split()))
X = list(map(int,input().split()))
X.sort()
output = 0
if N>=M:
    print(output)
else:
    Y = []
    for i in range(1,M):
        Y.append(X[i]-X[i-1])
    Y.sort()
    output += sum(Y[0:(M-N)])
    print(output)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache






MOD = 10**9+7
INF = float('inf')






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)



def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def gcd(a, b):
    while b:
        a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))


def int_log(n, a):
  count = 0
  while n>=a:
    n = n//a
    count += 1
  if a**count == n:
    return count
  else:
    return count+1





N,M = IL()
X = IL()

X.sort()
D = []

for i in range(M-1):
  D.append(X[i+1]-X[i])
  
D.sort()

if N>=M:
  PE(0)

P(sum(D[:M-N]))

Solution (Python):
n,m = map(int,input().split())
x = input().split()

if n >= m:
  	print(0)
else:
  for i in range(m):
    x[i] = int(x[i])
  x.sort()
  ans = x[-1] - x[0]
  
  b = []
  for i in range(m-1):
  	b.append(x[i+1]-x[i])
  b.sort()
  
  for i in range(1,n):
    
    ans -= b[-i]
  print(ans)

Solution (Python):
from itertools import *

n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
dis=[]
for i in range(1,m):
    dis.append(x[i]-x[i-1])
dis.sort()

if n>=m:
    print(0)
else:
    for i in range(n-1):
        dis.pop(-1)
    print(sum(dis))

Solution (Python):
import numpy as np

n, _ = map(int, input().split())
x = np.array(list(map(int, input().split())))

x.sort()
dist = x.max() - x.min()
x = np.diff(x)
x.sort()

ans = dist - x[::-1][:n - 1].sum()

print(ans)

Solution (Python):
import sys







INF = float('inf')
mod = 10**9+7
eps = 10**-7


def inp(): return int(sys.stdin.readline())


def inp_list(): return list(map(int, sys.stdin.readline().split()))


def lcm(x, y): return (x * y) // gcd(x, y)


N, M = inp_list()
X = inp_list()
X.sort()


if N >= M:
    print(0)
    exit()

d = [X[i + 1] - X[i] for i in range(M - 1)]


d.sort()
ans = sum(d[: M - 1 - (N - 1)])


    
print(ans)

Solution (Python):
import sys







INF = float('inf')
mod = 10**9+7
eps = 10**-7


def inp(): return int(sys.stdin.readline())


def inp_list(): return list(map(int, sys.stdin.readline().split()))


def lcm(x, y): return (x * y) // gcd(x, y)


N, M = inp_list()
X = inp_list()
X.sort()


if N >= M:
    print(0)
    exit()

d = [X[i + 1] - X[i] for i in range(M - 1)]


d.sort()

ans = 0
for i in range(M - 1 -  (N - 1)):
    ans += d[i]
print(ans)

Solution (Python):
import sys

input_methods=['clipboard','file','key']
using_method=1
input_method=input_methods[using_method]

tin=lambda : map(int, input().split())
lin=lambda : list(tin())
mod=1000000007



def main():
	
	n, m = tin()
	al = lin()
	
	al.sort()
	diff_al = [abs(vj-vi) for vi, vj in zip(al, al[1:])]
	
	
	diff_al.sort()
	
	if n == 1:
		ret = sum(diff_al)
	else:
		ret = sum(diff_al[:-(n-1)])
	print(ret)
	
	
	

isTest=False

def pa(v):
	if isTest:
		print(v)
		
def input_clipboard():
	import clipboard
	input_text=clipboard.get()
	input_l=input_text.splitlines()
	for l in input_l:
		yield l

if __name__ == "__main__":
	if sys.platform =='ios':
		if input_method==input_methods[0]:
			ic=input_clipboard()
			input = lambda : ic.__next__()
		elif input_method==input_methods[1]:
			sys.stdin=open('inputFile.txt')
		else:
			pass
		isTest=True
	else:
		pass
		
			
	ret = main()
	if ret is not None:
		print(ret)

Solution (Python):
n, m = map(int, input().split())
L = sorted(map(int, input().split()))
d = [L[i + 1] - L[i] for i in range(m - 1)]
d.sort(reverse=True)
print(sum(d[(n - 1):]))

Solution (Python):
n, m = map(int, input().split())
L = sorted(map(int, input().split()))
d = [0] * (m - 1)
for i in range(1, m):
    d[i - 1] = abs(L[i] - L[i - 1])
d = sorted(d, reverse=True)[(n - 1):]
print(sum(d))

Solution (Python):
N,M = map(int,input().split())
X = sorted(list(map(int,input().split())))

dX = [X[i+1]-X[i] for i in range(M-1)]
dX.sort()
p = N - 1
print(sum(dX[:-p]) if p != 0 else sum(dX))

Solution (Python):
n,m = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
l = x[-1] - x[0]
y = []
for i in range(m-1):
  y.append(x[i+1]-x[i])
y.sort(reverse=True)
print(l-sum(y[:(n-1)]))

Solution (Python):
N,M=map(int,input().split())
X=sorted([int(i)for i in input().split()])
print(sum(sorted([X[i+1]-X[i]for i in range(M-1)])[:max(M-N,0)]))

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()

from collections import defaultdict, deque, Counter
from sys import exit
import heapq
import math
import copy
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

N, M = getNM()
X = getList()
X. sort()
Xalta = []
for i in range(M - 1):
    Xalta.append(-1 * abs(X[i + 1] - X[i]))
heapq.heapify(Xalta)

for i in range(N - 1):
    if len(Xalta) > 0:
        heapq.heappop(Xalta)
print(sum(Xalta) * -1)

Solution (Python):
m, n = map(int, input().split())
a = [int(x) for x in input().split()]
a.sort()
b = [a[i+1]-a[i] for i in range(n-1)]
b.sort(reverse=True)

print(a[-1]-a[0]-sum(b[:min([m-1, n-1])]))

Solution (Python):

import re
import math
from collections import defaultdict
from collections import deque
from fractions import Fraction
import itertools
from copy import deepcopy
import random
import time
import os
import queue
import sys
import datetime
from functools import lru_cache

readline=sys.stdin.readline
sys.setrecursionlimit(2000000)

alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def is_pow(a,b):
    now=b
    while now<a:
        now*=b
    if now==a:return True
    else:return False
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def get_facs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def get_primes(n,type="int"):
    if n==0:
        if type=="int":return []
        else:return [False]
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(a,b,c):
    if a:return b
    else:return  c
def join(A,c=""):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n,type_="dict"):
    b = 2
    list_ = []
    while b * b <= n:
        while n % b == 0:
            n //= b
            list_.append(b)
        b+=1
    if n > 1:list_.append(n)
    if type_=="dict":
        dic={}
        for a in list_:
            if a in dic:
                dic[a]+=1
            else:
                dic[a]=1
        return dic
    elif type_=="list":
        return list_
    else:
        return None
def pm(x):
    return x//abs(x)
def inputintlist():
    return list(map(int,input().split()))

def main():
    N,M=inputintlist()
    X=inputintlist()
    X.sort()
    if N>=M:
        print(0)
    else:
        kukan=[]
        for a in range(M-1):
            kukan.append(X[a+1]-X[a])
        kukan.sort()
        kukan.reverse()
        ans=X[-1]-X[0]
        ans-=sum(kukan[:N-1])
        print(ans)
main()

Solution (Python):
def main():
    N, M = [int(v) for v in input().split(' ')]
    X = sorted([int(v) for v in input().split(' ')])

    if N >= M:
        print(0)
        return

    l = []
    x0 = X[0]
    for x in X[1:]:
        dx = x - x0
        l.append(dx)
        x0 = x

    sl = sorted(l)

    count = 0
    for v in sl[0:M - N]:
        count += v
    print(count)


main()

Solution (Python):
import sys











stdin = sys.stdin
sys.setrecursionlimit(10 ** 7)
MIN = -10 ** 9
MOD = 10 ** 9 + 7
INF = float("inf")
IINF = 10 ** 18

def main():
    
    n,m = map(int, stdin.readline().rstrip().split())
    x = list(map(int, stdin.readline().rstrip().split()))
    
    
    
    
    if n>m:
        print(0)
        exit()
    spl = n-1
    sa = [0]*(m-1)
    x.sort()
    for i in range(m-1):
        sa[i] = x[i+1] - x[i]
    sa.sort()
    i = m-n
    print(sum(sa[:i]))



main()

Solution (Python):
N,M=map(int,input().split())
if N>=M:
    X=[int(i) for i in input().split()]
    print(0)
else:
    X=[int(i) for i in input().split()]
    a=sorted(X)
    d=[]
    for i in range(M-1):
        d.append(a[i+1]-a[i])
    k=sorted(d)
    print(sum(k[:M-N]))

Solution (Python):
N, M = map(int, input().split())
X = [int(x) for x in input().split()]
X.sort(reverse=True)
X_diff = []
for i in range(len(X)-1):
    X_diff.append(X[i] - X[i+1])
X_diff.sort()
if N < M:
    print(sum(X_diff[:M-N]))
else:
    print(0)

Solution (Python):

import sys
input = sys.stdin.readline









N,M = map(int,input().split())
X = list(map(int,input().split()))

if N >= M:
    print(0)
else:
    X.sort()
    D = []
    for i in range(M-1):
        D.append(X[i+1]-X[i])
    D.sort()
    print(sum(D[0:M-N]))

Solution (Python):
n, m = map(int, input().split())

if n >= m:
    print(0)
    exit()
    
lis = list(map(int, input().split()))
lis.sort()

res = []
for i in range(m - 1):
    res.append(lis[i + 1] - lis[i])
res.sort()

l = len(res)
k = n - 1

print(sum(res[:l - k]))

Solution (Python):
n, m = map(int, input().split())
k = sorted(list(map(int, input().split())))

if n >= m:
    print(0)
    exit()
dis = []
for i in range(m-1):
    dis.append(k[i+1] - k[i])

dis.sort()
dis.reverse()
sub = 0

for i in range(n-1):
    sub += dis[i]
    
print(sum(dis) - sub)

Solution (Python):
import itertools
import math
import fractions
import functools
import copy
n, m = map(int, input().split())
x  = list(map(int, input().split()))

sub = []
x.sort()
for i in range(m-1):
    sub.append(abs(x[i]-x[i+1]))

sub.sort(reverse=True)
if n >= m:
    print(0)
    quit()
for i in range(n-1):
    sub[i] = 0
print(sum(sub))

Solution (Python):
import sys
from heapq import heappush, heappop
def input(): return sys.stdin.readline().strip()


def main():
    N, M = map(int, input().split())
    X = list(map(int, input().split()))
    if M <= N:
        print(0)
        return
    X.sort(reverse=True)
    diff = []
    pre = X.pop()
    for i in range(M - 1):
        cur = X.pop()
        heappush(diff, cur - pre)
        pre = cur
    ans = 0
    for _ in range(M - N):
        ans += heappop(diff)
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
n, m = map(int, input().split())
x = list(map(int, input().split()))
if n >= m:
    print(0)
    exit()
x.sort()
l = []
for i in range(m - 1):
    l.append(x[i + 1] - x[i])
l.sort()
print(sum(l[: m - n]))

Solution (Python):
n, m = map(int, input().split())
Xm = list(map(int, input().split()))
if n >= m:
    print(0)
else:
    Xm.sort()
    check = [Xm[i+1] - Xm[i] for i in range(m-1)]
    check.sort(reverse=True)
    print(sum(check) - sum(check[:n-1]))

Solution (Python):
n, m = map(int, input().split())
Xm = list(map(int, input().split()))
Xm.sort()
check = [Xm[i+1] - Xm[i] for i in range(m-1)]
check.sort()
print(sum(check[:max(m-n, 0)]))

Solution (Python):



import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n,m=MI()
lis=LI()
if n>=m:
    print(0)
    sys.exit()
lis.sort()
dis=[]
for i in range(m-1):
    dis.append(lis[i+1]-lis[i])
ans=0
dis.sort()
for i in range(m-n):
    ans+=dis[i]
print(ans)

Solution (Python):
N, M = map(int, input().split(' '))
if N >= M:
    print(0)
else:
    points = sorted(tuple(map(int, input().split(' '))))
    distances = sorted([abs(p1 - p2) for p1, p2 in zip(points, points[1:])], reverse=True)
    print(sum(distances[N - 1:]))

Solution (Python):
n, m = [int(i) for i in input().split()]
x = sorted([int(i) for i in input().split()])
a = list(reversed(sorted([x[i+1] - x[i] for i in range(m-1)])))
print(sum(a[n-1:]))

Solution (Python):


import numpy as np

import math

n,m = map(int,input().split())
A = list(map(int,input().split()))
A.sort()
B = [-A[i]+A[i+1] for i in range(m-1)]
B.sort()
print(sum(B[0:max(m-n,0)]))

Solution (Python):
N, M = map(int, input().split())

if (M <= N):
    print(0)
else:
    Xs = list(map(int, input().split()))
    Xs.sort()
    W = Xs[-1] - Xs[0]
    Ds = [Xs[i+1]-Xs[i] for i in range(M-1)]
    Ds.sort(reverse=True)

    gaps = 0
    for i in range(N-1):
        gaps += Ds[i]

    print(W-gaps)

Solution (Python):
import heapq
n,m = map(int,input().split())
x_input = sorted(list(map(int,input().split())))

cost_li = []
for i in range(m-1):
    heapq.heappush(cost_li,-(x_input[i+1]-x_input[i]))

for i in range(n-1):
    if len(cost_li)==0:
        print(0);exit()
    heapq.heappop(cost_li)

print(-sum(cost_li))

Solution (Python):
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))

n,m = iim()
X = iil()
X.sort()

dif = []
for i in range(1,m):
    dif.append(X[i]-X[i-1])

dif.sort(reverse=True)


print(X[-1]-X[0]-sum(dif[:n-1]))

Solution (Python):
n,m = map(int, input().split())
T = list(map(int, input().split()))

if n >= m:
    print(0)
    exit()

T.sort()
diff = []
for i in range(1,m):
    diff.append(T[i]-T[i-1])
diff.sort(reverse=True)
print(sum(diff[n-1:]))

Solution (Python):

"""
全探索は無理なオーダー
N個のこま，
M - N回の移動が必要
−＞間の距離の長いのを移動しないように配置すれば良い
"""
N, M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()
if N >= M:
    print(0)
    exit()

dist = [X[i+1] - X[i] for i in range(M-1)]
dist.sort(reverse=True)

count = sum(dist)
for i in range(N-1):
    count -= dist[i]

print(count)

Solution (Python):
import heapq

N,M = (int(x) for x in input().split())
X = list(map(int, input().split()))
if N >= M:
    print('0')
else:
    heapq.heapify(X)
    t1 = heapq.heappop(X)
    diff = []
    for i in range(M-1):
        t2 = heapq.heappop(X)
        diff.append(t2-t1)
        t1 = t2
    heapq.heapify(diff)
    ans = 0
    for i in range(M-N):
        ans += heapq.heappop(diff)
    print(ans)

Solution (Python):
n, m = map(int, input().split())
if n >= m:
    print(0)
    exit()
l = list(map(int, input().split()))
l.sort()
t = l[0]
a = []
for i in l[1:]:
    a.append(i-t)
    t = i
a.sort(reverse=True)
print(sum(a[n-1:]))

Solution (Python):
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18


n, m = Is()
X = LI()
X.sort()
D = []
for i in range(1, m):
    D.append(X[i]-X[i-1])
D.sort(reverse=True)
print(X[-1]-X[0]-sum(D[:n-1]))

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    N, M = map(int, input().split())
    X = list(map(int, input().split()))
    X.sort()

    dist = []
    for i in range(1, M):
        dist.append(X[i] - X[i - 1])

    dist.sort(reverse=True)

    if N >= M:
        print(0)
    else:
        
        ans = sum(dist[N - 1 :])
        print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

"""
Created on Wed May 13 13:45:08 2020

@author: shinba
"""
import sys
n,m = map(int,input().split())

X = list(map(int,input().split()))

if n >= m:
    print(0)
    sys.exit()

sub = []
X.sort()

for i in range(m-1):
    sub.append(X[i+1]-X[i])

sub.sort()

for i in range(n-1):
    sub.pop()

print(sum(sub))

Solution (Python):


import sys






















def main():
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, m = mi()
    X = lmi()
    X.sort()
    if m <= n:
        print(0)
    else:
        diff = [X[i] - X[i-1] for i in range(1, m)]
        diff.sort()
        print(sum(diff[:m-n]))


if __name__ == "__main__":
    main()

Solution (Python):
N,M=map(int,input().split())
X=sorted(list(map(int,input().split())))

if N >= M:
  print(0)
  exit()
D=[0]*(M-1)
for i in range(1,M):
  D[i-1] = X[i]-X[i-1]
D.sort()
D.reverse()
D_pass=0
for i in range(N-1):
  D_pass+=D[i]
print(X[-1]-X[0]-D_pass)

Solution (Python):

import collections
import itertools as it
import math

 


n, m  = map(int, input().split())
x  = list(map(int, input().split()))




x.sort()
q = [x1 - x2 for x1, x2 in zip(x[1:], x[:-1])]
q = sorted(q)[::-1]

print(sum(q[n-1:]))

Solution (Python):


N, M = map(int, input().split())
X = sorted(list(map(int, input().split())))

D = {}

for i in range(M-1):
    D[(X[i],X[i+1])] = X[i+1] - X[i]

s_D = sorted(D.items(), key=lambda x:x[1])[::-1]
A = s_D[N-1:]
ans = 0
for a in A:
    ans += a[1]
print(ans)

Solution (Python):

import collections
import itertools as it
import math

 


n, m  = map(int, input().split())
x  = list(map(int, input().split()))




x.sort()
q = [x1 - x2 for x1, x2 in zip(x[1:], x[:-1])]
q = sorted(q)[::-1]

print(sum(q[n-1:]))

Solution (Python):
N, M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()

if N >= M:
    print(0)
else:
    sub = [0]*(M-1)
    for i in range(M-1):
        sub[i] = X[i+1]-X[i]
    sub.sort()

    ans = 0
    for i in range(M-N):
        ans += sub[i]
    print(ans)