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



Sample input:
2 5
10 12 1 2 14


Sample output:
5

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
if N < M:
    X.sort()
    XX = [X[i + 1] - X[i] for i in range(M - 1)]
    XX.sort()
    ans = sum(XX[:M - N])
else:
    ans = 0
print(ans)

Submission status: Accepted

Solution code:
import sys


N, M = map(int, sys.stdin.readline().split())
X = list(map(int, sys.stdin.readline().split()))

if N >= M:
    ans = 0
    print(ans)
    sys.exit()

X.sort()
dif_list = []
for i in range(len(X) - 1):
    dif_list.append(X[i+1] - X[i])
dif_list.sort()
count = 0
ans = 0
for i in dif_list:
    ans += i
    count += 1
    if count == M - N:
        break

print(ans)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
X = list(map(int,input().split()))
X.sort()
distance = []
for i in range(1,M):
    distance.append(X[i]-X[i-1])
distance.sort(reverse = 1)
print(sum(distance[N-1:]))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
x = list(map(int,input().split()))
x_ = []
x.sort()
count = 0

if n>=m:
    print(count)
else:
    for i in range(1,len(x)):
        x_.append(x[-i]-x[-i-1])
    x_.sort()
    count = sum(x_[0:m-n])
    print(count)

Submission status: Accepted

Solution code:
import sys

from collections import deque
# q = deque(); q.append(x); q.appendleft(x); q.pop() -> x; q.popleft() -> x
from collections import defaultdict
# d = defaultdict(lambda: []); d[key] -> []
import heapq
# hq = []; heapq.heappush(hq, x); heapq.heappop(hq) -> x; heapq.heappushpop(hq, x) -> x
import bisect
# i = bisect.bisect_left([1,2,3,4], 1.5); i = bisect.bisect_right([4,3,2,1], 1.5)

#import numpy as np
#from scipy.misc import comb

s2nn = lambda s: [int(c) for c in s.split(' ')]
ss2nn = lambda ss: [int(s) for s in ss]
ss2nnn = lambda ss: [s2nn(s) for s in ss]
i2s = lambda: sys.stdin.readline().rstrip()
i2n = lambda: int(i2s())
i2nn = lambda: s2nn(i2s())
ii2ss = lambda n: [sys.stdin.readline().rstrip() for _ in range(n)]
ii2nn = lambda n: ss2nn(ii2ss(n))
ii2nnn = lambda n: ss2nnn(ii2ss(n))

def main():
    N, M = i2nn()
    X = i2nn()
    if N >= M:
        print(0)
        return
    X.sort()
    D = [X[i]-X[i-1] for i in range(1, M)]
    D.sort()
    n = sum(D[:M-N])
    print(n)

main()

Submission status: Accepted

Solution code:
NM=list(map(int,input().split()))
inp=list(map(int,input().split()))

N=NM[0]
M=NM[1]

inp.sort()
dis=[]
#print(inp)
c=0
for r in inp[:-1]:
    dis.append(inp[c+1]-inp[c])
    c+=1
#print(dis)
dis.sort()
for de in range(N-1):
    if len(dis)>0:    
        del dis[-1]
#print(dis)
print(sum(dis))

Submission status: Accepted

Solution code:
import bisect
import os
from collections import Counter, deque
from fractions import gcd
from functools import lru_cache
from functools import reduce
import functools
import heapq
import itertools
import math
import numpy as np
import re
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")

N, M = list(map(int, sys.stdin.readline().split()))
X = list(map(int, sys.stdin.readline().split()))

X = np.array(X)
X.sort()
diffs = np.diff(X)
diffs.sort()
print(diffs[:max(0, M - N)].sum())

Submission status: Accepted

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

Submission status: Accepted

Solution code:
def resolve():
    (N, M) = list(map(int, input().split(" ")))
    Xs = list(map(int, input().split(" ")))

    Xs.sort()
    diffs = [(i, Xs[i] - Xs[i-1]) for i in range(1, M)]
    diffs = sorted(diffs, key=lambda x: x[1], reverse=True)
    cnt = 0
    for i in range((N-1), len(diffs)):
        cnt += diffs[i][1]

    print(cnt)
    

if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
import sys

diff = []

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

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

X.sort()

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

diff.sort()

for i in range(N-1):
    diff.pop()

print(sum(diff))

Submission status: Accepted

Solution code:
import sys
from collections import deque


diff = deque()

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

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

X.sort()

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

diff = list(diff)
diff.sort()

for i in range(N-1):
    diff.pop()

print(sum(diff))

Submission status: Accepted

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

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

Submission status: Accepted

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

if N < M:
    cost = []
    for i in range(M-1):
        cost.append(abs(X[i] - X[i+1]))
    cost = sorted(cost, reverse=True)
    del cost[:N-1]
    
    print(sum(cost))
else:
    print(0)

Submission status: Accepted

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

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

diff = m - n
dist_list = []
x.sort()
for i in range(len(x) - 1):
    distance = x[i+1] - x[i]
    dist_list.append(distance)

dist_list.sort()
ans = sum(dist_list[0:diff])

print(ans)

Submission status: Accepted

Solution code:
###template###
import sys
def input(): return sys.stdin.readline().rstrip()
def mi(): return map(int, input().split())
###template###

N, M = mi()

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

Xs = sorted(list(mi()))
gaps = [0] * (M-1)

for i in range(M-1):
  gaps[i] = Xs[i+1] - Xs[i]

gaps = sorted(gaps, reverse=True)

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

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()
Y = [0] * (M-1)
for i in range(1, M):
    Y[i-1] = X[i] - X[i-1]
Y.sort()
if N>=M:
    print(0)
    exit()
s = 0
for i in range(M-N):
    s += Y[i]
print(s)

Submission status: Accepted

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

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

diff = M - N

X_sorted = sorted(X)

distance_list = []

for i in range(len(X_sorted)-1):
    distance = abs(X_sorted[i] - X_sorted[i+1])
    distance_list.append(distance)

distance_list.sort()

ans = sum(distance_list[0:diff])

print(ans)

Submission status: Accepted

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

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

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

    diff.sort(reverse=True)

    ans = X[M-1]-X[0] - sum(diff[:N-1])
    print(ans)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
x = [int(_) for _ in input().split()]
if n >= m:
    print(0)
else:
    x.sort()
    diff = [x[i+1]-x[i] for i in range(m-1)]
    diff.sort(key = lambda y:-y)
    ans = x[m-1] - x[0]
    for i in range(n-1):
        ans -= diff[i]
    print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

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

# Xを昇順ソート
X = sorted(X)

# 1番左の要素は必ず選び
# 残りの(N-1)個は階差数列の大きい順に選んだときが最適

# 階差数列: (X[k]-X[k-1], k)
Xd = [None] * (M - 1)
for i in range(1, M):
    Xd[i-1] = (X[i] - X[i-1], i)

# 階差数列を昇順ソート
Xd = sorted(Xd)

# コマを置く座標のインデックス
K = []

# 残りのM-1個を選ぶ
for i in range(N-1):
    if len(Xd) == 0:
        break

    a = Xd.pop(-1) # lastのpopはO(1)
    K.append(a[1])
    
# 左端以外について、コマを置いた座標と左隣の座標の差 == 節約できた移動量
s = 0
for k in K:
    s += X[k] - X[k-1]

l = X[-1] - X[0] - s
print(l)

Submission status: Accepted

Solution code:
import sys
# メタデータ入力
n, m = map(int,input().split())

if n >= m:
  print(0)
  sys.exit()
# 座標入力
pos = list(map(int,input().split()))
# ソート
pos.sort()

# 差分計算
distances = []
for i, x in enumerate(pos):
  if i == 0:
    continue
  distances.append(abs(pos[i] - pos[i-1]))

distances.sort()
for i in range(n-1):
	distances.pop()
print(sum(distances))

Submission status: Accepted

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

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

X.sort()

# 隣接点の間の距離が長い順で分割する
# おけるコマの個数-1だけ辺を取り除ける

maxDist = X[-1] - X[0]

dist = [0] * (M-1)

# 間の距離を計算
for i in range(M-1) :
    dist[i] = X[i+1] - X[i]

dist.sort(reverse=True)

for i in range(min(N-1,M-1)) :
    maxDist -= dist[i]

print(maxDist)

Submission status: Accepted

Solution code:
import numpy as np

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

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

## マスの間の距離を計算して、そのうち小さいもの(M-N)個だけ移動する
X.sort()
dist = [X[i+1]-X[i] for i in range(M-1)]
dist_small = np.array(dist.sort())
dist_cumsum = np.cumsum(dist)
print(dist_cumsum[M-N-1])

Submission status: Accepted

Solution code:
N,M=map(int,input().split())
X=list(map(int,input().split()))
X.sort()
cost=[0]*(M-1)
for i in range(M-1):
  cost[i]=X[i+1]-X[i]
cost.sort(reverse=True)
print(sum(cost[N-1:]))

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  n,m=LI()
  l=LI()

  l.sort()
  l2=[]
  for i in range(len(l)-1):
    l2.append(l[i+1]-l[i])

  l2.sort()

  if n==1:
    return sum(l2)
  return sum(l2[:-n+1])

print(main())

Submission status: Accepted

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

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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
if N >= M:
	print(0)
else:
	X.sort()
	Y = [0] * (M - 1)
	for i in range(M - 1):
		Y[i] = X[i+1] - X[i]
	Y.sort(reverse = True)
	print(max(X) - min(X) - sum(Y[:N - 1]))

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
X=[0]*(m-1)
for i in range(m-1):
  X[i]=x[i+1]-x[i]
X.sort(reverse=True)
if n>=m:
  print(0)
else:
  print(max(x)-min(x)-sum(X[:n-1]))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

input = sys.stdin.readline

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

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

    diff.sort(reverse=True)
    print(sum(diff[N-1:]))

main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N, M, *X = map(int, open(0).read().split())
X.sort()

y = sorted([X[i + 1] - X[i] for i in range(len(X) - 1)], reverse=True)
print(sum(y[N - 1:]))

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
x=sorted([int(i) for i in input().split()])
if n>=m:
    print(0)
else:
    r=[]
    for i in range(m-1):
        r.append(x[i+1]-x[i])
    r.sort()
    if n!=1:
        print(sum(r[:-n+1]))
    else:
        print(sum(r))

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import heapq
N,M=list(map(int,input().split()))
Xs = list(map(int,input().split()))
Xs.sort()

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

pq = []
for i in range(M-1):
    heapq.heappush(pq, Xs[i] - Xs[i+1])

for i in range(N-1):
    heapq.heappop(pq)

res = 0
while pq:
    res -= heapq.heappop(pq)

print(res)

Submission status: Accepted

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

Submission status: Accepted

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

X = sorted([int(x) for x in input().split()])

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

  
print(sum(sorted(Y,reverse=True)[N-1:]))

Submission status: Accepted

Solution code:
import numpy as np

N,M= map(int, input().split())
A = np.array(sorted(list(map(int , input().split()))))
diff = np.diff(A)
sort_list = list(np.argsort(diff)[::-1])
dev_place = sorted(sort_list[:N-1]) + [len(A)]
start_point = 0
ans = 0

for i in dev_place:
	tmp = A[start_point:i+1]
	ans += max(tmp)- min(tmp)
	start_point = i+1

print(ans)

Submission status: Accepted

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

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

X_array.sort()
# print(X_array)
diff_array = [(X_array[i + 1] - X_array[i]) for i in range(M - 1)]
# print(diff_array)
diff_array.sort()
if N != 1:
    print(sum(diff_array[:-(N - 1)]))
else:
    print(sum(diff_array))

Submission status: Accepted

Solution code:
N, M, *X = map(int, open(0).read().split())
X.sort()

y = sorted([X[i + 1] - X[i] for i in range(len(X) - 1)], reverse=True)
print(sum(y[N - 1:]))

Submission status: Accepted

Solution code:
N, M, *X = map(int, open(0).read().split())
X.sort()

y = sorted([X[i + 1] - X[i] for i in range(len(X) - 1)])
if N == 1:
    print(sum(y))
else:
    print(sum(y[:-(N - 1)]))

Submission status: Accepted

Solution code:
def sub():
    N, M = [int(e) for e in input().split()]
    Xs = [int(e) for e in input().split()]
    if N >= M:
        print(0)
        return

    Xs = sorted(Xs)
    ds = [Xs[i+1] - Xs[i] for i in range(M-1)]
    ds = sorted(ds)
    # print(ds) 
    if N == 1:
        print(sum(ds))
        return
    nb_take = N - 1
    print(sum(ds[:-nb_take]))


if __name__ == "__main__":
    sub()

Submission status: Accepted

Solution code:
from __future__ import print_function
# import numpy as np
# import numpypy as np
import sys
import math
import string
import fractions
import re
import array
import copy
import functools
import operator

import collections
import itertools
import bisect
import heapq


from heapq import heappush
from heapq import heappop

# from itertools import accumulate
# from collections import deque
import random




def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)


def main():
    n,m = map(int, input().split())
    l = sorted(list(map(int, input().split())))
    
    l_diff = [(l[i+1] - l[i]) for i in range(len(l)-1)]
    # eprint(l)
    # eprint(l_diff)
    l_diff.sort()
    # eprint(l_diff)

    for i in range(min(n-1,len(l_diff))):
        l_diff.pop()
    print(sum(l_diff))
    # for i in range(0,n-1):
    #     sum += l[i+1] -l[i]

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
x=sorted(list(map(int,input().split())))
if n>=m:
    print(0)
else:
    x_interval=[]
    for i in range(0,m-1):
        x_interval.append(-(x[i]-x[i+1]))
    x_interval=sorted(x_interval,reverse=True)
    print(x[m-1]-x[0]-sum(x_interval[:(n-1)]))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
ans = 0
if (M-1)-(N-1) <= 0:
    pass
else:
    X.sort()
    dist = [X[i+1]-X[i] for i in range(M-1)]
    dist.sort()
    for i in range((M-1)-(N-1)):
        ans += dist[i]
print(ans)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
X.sort()
D = [X[i+1] - X[i] for i in range(len(X)-1)]
D.sort()
if N>=M: print(0)
else:
  newD = D[:len(D)-(N-1)]
  print(sum(newD))

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
xs = list(map(int, input().split()))
xs = sorted(xs)

ds = [xs[i+1] - xs[i] for i in range(m-1)]
ds = sorted(ds, reverse=True)

print((xs[-1] - xs[0]) - sum(ds[:n-1]))

Submission status: Accepted

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

data = [int(s) for s in input().split()]
data.sort()
l = []
if n >= m:
    print(0)
else:
    for i in range(m-1):
        l.append(data[i+1]-data[i])
    l.sort(reverse = True)

    x = 0
    for i in range(n-1):
        x += l[i]
    print(data[m-1] - data[0] - x)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))
count = [0] * (m-1)
ans = 0

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

print(ans)

Submission status: Accepted

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

# 訪れなくてもいい区間の最大値を求める
L = []
for i in range(0, M-1):
    L.append(X[i+1] - X[i])

print(X[-1] - X[0] - sum(sorted(L, reverse=True)[:N-1]))

Submission status: Accepted

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

if len(X) == 1:
    print(0)
    exit()

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

d = sorted(d, reverse=True)
ans = abs(X[-1] + (X[0] * -1)) - sum(d[:N - 1])
print(ans)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = sorted(list(map(int, input().split())))
     
L = sorted([X[i+1] - X[i] for i in range(M-1)], reverse=True)
del L[:N-1]
     
print(sum(L))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = sorted([int(c) for c in input().split()])

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

undeveloped_lengths = sorted(
    [X[i] - X[i - 1] - 1 for i in range(M - 1, 0, -1)], reverse=True)
length_have_to_be_covered = (X[-1] - X[0] + 1) - sum(
    undeveloped_lengths[:N - 1])
print(length_have_to_be_covered - N)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
X = sorted(map(int,input().split()))
x = []
for i in range(M-1):
	x.append(abs(X[i]-X[i+1]))
x.sort(reverse=1)
if N >= M:
	print(0)
else:
	print(sum(x[N-1:]))

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
x = [i for i in map(int,input().split())]

x.sort()
diff = []
for i in range(m-1):
    diff.append(x[i+1] - x[i])
diff.sort(reverse= True)
ans = sum(diff) - sum(diff[0:n-1])
print(ans)

Submission status: Accepted

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

L = sorted([X[i+1] - X[i] for i in range(M-1)], reverse=True)
del L[:N-1]

print(sum(L))

Submission status: Accepted

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

def main():
  x = sorted(X)
  costs = []
  for i in range(M-1):
    costs.append(abs(x[i] - x[i+1]))
  costs.sort()
  ans = sum(costs[:(-(N-1) if N != 1 else M)])
  print(ans)

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
N, M = [int(n) for n in input().split()]
S = input().split() if M != 1 else [input()]
X = [int(s) for s in S]

def main():
    x = sorted(X)
    costs = []
    for i in range(M - 1):
        costs.append(abs(x[i] - x[i + 1]))
    costs.sort()
    ans = sum(costs[:(-(N - 1) if N != 1 else M)])
    print(ans)

if __name__== '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, X: "List[int]"):
    X.sort()
    L = []
    for i in range(1,M):
        L.append( X[i] - X[i-1])
    L.sort(reverse=True)

    print((X[-1] - X[0]) - sum(L[0:(N-1)]))


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    X = [ int(next(tokens)) for _ in range(M) ]  # type: "List[int]"
    solve(N, M, X)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

L = [X[i + 1] - X[i] for i in range(M - 1)]
L = sorted(L, reverse=True)
result = X[-1] - X[0] - sum(L[:N - 1])
print(result)

Submission status: Accepted

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

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

M_lst.sort()

diff_lst = []
for i in range(M-1):
  diff_lst.append(M_lst[i+1] - M_lst[i])

diff_lst.sort()

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

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
if n<m:
    l=sorted(list(map(int,input().split())))
    s=[]
    for i in range(m-1):s.append(l[i+1]-l[i])
    s.sort(reverse=True)
    ans=l[-1]-l[0]
    if m>1:
        for i in range(n-1):ans-=s[i]
    print(ans)
else:print(0)

Submission status: Accepted

Solution code:
[n, m] = [int(i) for i in input().split()]
x = [int(i) for i in input().split()]
x.sort()

diff = [x[i + 1] - x[i] for i in range(len(x) - 1)]
diff.sort(reverse=True)
print(sum(diff[n - 1:]))

Submission status: Accepted

Solution code:
n,m = map(int, input().split())
X = list(map(int, input().split()))
X.sort()

Dis = [X[i+1]-X[i] for i in range(m-1)]
Dis.sort()

print(sum(Dis[:m-n]) if m > n else 0)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
X = list(map(int,input().split()))
X2 = sorted(X)
div_X = []
for i in range (M-1):
    div_X.append(X2[i+1]-X2[i])
Y = sorted(div_X)


if N >= M:
    ans = 0
else:
    ans = sum(Y[0:M-N])

print (ans)

Submission status: Accepted

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

if n >= m:
    ans = 0
else:
    x.sort()
    cheak = [0]*(m-1)
    
    for i in range(m-1):
        cheak[i] = abs(x[i+1]-x[i])
    cheak.sort(reverse=True)
    
    for j in range(n-1):
        cheak.pop(0)
    
    ans = sum(cheak)
print(ans)

Submission status: Accepted

Solution code:
#C-117
n, m = [int(i) for i in input().split()]
x = [int(i) for i in input().split()]
if n >= m:
  print(0)
elif n == 1:
  print(max(x) - min(x))
else:
  x.sort()
  x_diff = []
  for mi in range(m-1):
    x_diff.append([x[mi+1]-x[mi], mi])
  #print(x_diff)
  x_diff.sort(reverse = True)
  #print(x_diff)
  split_list = []
  for ni in range(n-1):
    split_idx = x_diff[ni][1]
    split_list.append(split_idx)
  split_list.sort()
  #print(split_list)
  #print(x)
  ans = 0
  ans += x[split_list[0]] - x[0]
  #print("ans",ans)
  for ni in range(n-2):
    l = split_list[ni]+1
    r = split_list[ni+1]
    ans += x[r] - x[l]
    #print("ans",ans)
  ans += x[-1] - x[split_list[-1]+1]
  print(ans)

Submission status: Accepted

Solution code:
N,M = map(int,input().split())
X_list = list(map(int,input().split()))
X_list.sort()
L_list = []
for i in range(1,M):
    L_list.append(X_list[i]-X_list[i-1])
L_list.sort()
if N >= M:
    print('0')
else:
    print(sum(L_list[:M-N]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
C - Streamline
https://atcoder.jp/contests/abc117/tasks/abc117_c

"""
import sys


def solve(N, M, positions):
    gaps = sorted([b-a for a, b in zip(positions, positions[1:])])
    if len(gaps) < N:
        return 0
    return sum(gaps[:-(N-1)]) if N > 1 else sum(gaps)


def main(args):
    N, M = map(int, input().split())
    positions = sorted(map(int, input().split()))
    ans = solve(N, M, positions)
    print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())

N,M = inpl()
XX = inpl()
XX.sort()
dist = []
for i in range(1,M):
    dist.append(XX[i] - XX[i-1])

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

Submission status: Accepted

Solution code:
from itertools import combinations
n, m = map(int, input().split(" "))
if n >= m:
  print(0)
else:
  ls = list(sorted(map(int, input().split(" "))))
  total = ls[-1] - ls[0]
  sections = sorted([ls[i+1]-ls[i] for i in range(m-1)], reverse=True)
  print(total-sum(sections[:n-1]))

Submission status: Accepted

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

if N >= M:
    print(0)
else:
    X.sort()
    
    spaces = []
    now = X[0]
    
    for i in range(1,len(X)):
        spaces.append(X[i]-now)
        now = X[i]
    
    sortSpaces = sorted(spaces, reverse = True)
    
    maxN = sortSpaces[:N-1]
    
    print(sum(spaces)-sum(maxN))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

N, M = [int(i) for i in input().split()]
X = list(map(int, input().split()))

sorted_X = sorted(X)

diff_list = []
for i, j in zip(sorted_X, sorted_X[1:]):
    diff_list.append(j - i)

ans = sorted(diff_list, reverse=True)[N-1:]
print(sum(ans))

Submission status: Accepted

Solution code:
N,M = [ int(it) for it in input().split() ]
li = [ int(it) for it in input().split() ]

if (M==1):
  print(0)
else:
  li.sort()
  di = [ li[i+1] - li[i] for i in range( len(li) - 1 ) ]
  di.sort()

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

Submission status: Accepted

Solution code:
n,m=map(int, input().split())
x=list(map(int, input().split()))
x=sorted(x)
y=[abs(i-j) for(i,j) in zip(x[1:],x[:-1])]
y=sorted(y)
z=sum(y[:m-n])
print(z if n<m else 0)

Submission status: Accepted

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

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

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

diff_list.sort(reverse=True)

sum_big_diff = 0
if M > 1:
    for i in range(N - 1):
        sum_big_diff += diff_list[i]

print(X[M - 1] - X[0] - sum_big_diff)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

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


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

for _ in range(n-1):
    sub.pop(-1)
print(sum(sub))

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
x=sorted(list(map(int,input().split())))
s=[]
for i in range(m-1):
    s.append(x[i+1]-x[i])
s=sorted(s,reverse=True)
ans=0
for j in range(len(s)):
    if n>1:
        n-=1
    else:
        ans+=s[j]

print(ans)

Submission status: Accepted

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

X = sorted(X)

gaps = sorted([X[i+1]-X[i] for i in range(len(X)-1)],reverse=True)

if N > len(gaps):
  print(0)
else:
  print(X[-1]-X[0]-sum(gaps[:N-1]))

Submission status: Accepted

Solution code:
import sys

N, M = map(int, input().split())
if N >= M:
    print(0)
    sys.exit(0)

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

distance_list = [b - a for a, b in zip(X, X[1:])]
distance_list.sort()

if N != 1:
    print(sum(distance_list[:-N+1]))
else:
    print(sum(distance_list))

Submission status: Accepted

Solution code:
import sys

N, M = map(int, input().split())
if N >= M:
    print(0)
    sys.exit(0)

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

distance_list = [b - a for a, b in zip(X,X[1:])]
distance_list.sort()

print(sum(distance_list[:M-N]))

Submission status: Accepted

Solution code:
import sys

N, M = map(int, input().split())
if N >= M:
    print(0)
    sys.exit(0)

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

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

distance_list.sort(reverse=True)
print(X[-1] - X[0] - sum(distance_list[:N-1]))

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(sorted(map(int, input().split())))
if N >= M:
  print('0')
else:
  d = []
  ans = X[-1] - X[0]
  for i in range(M - 1):
    d.append(X[i + 1] - X[i])
  ans -= sum(list(sorted(d, reverse=True))[0:N - 1])
  print(ans)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
fl = []

for i in range(len(l)-1):
  fl.append(l[i+1]-l[i])

fl.sort()

total = 0
for j in range(len(fl)-n+1):
  total+=fl[j]

print(total)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
X = list(map(int, input().split()))

X.sort()
if n >= m:
    print(0)
else:
    Y = []
    for i in range(m - 1):
        Y.append(X[i + 1] - X[i])
    Y.sort(reverse = True)
    ans = X[m - 1] - X[0]
    for i in range(n - 1):
        ans -= Y[i]
    print(ans)

Submission status: Accepted

Solution code:
a,b=map(int,input().split())
c=[int(i) for i in input().split()]
c.sort()
d=c[-1]-c[0]
for i in range(b-1):
    c[-i-1]=c[-i-1]-c[-i-2]
c[0]=0
c.sort()
print([sum(c[:b-a+1]),0][a >=b])

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
x = sorted(map(int, input().split()))
if n >= m:
    print(0)
else:
    dif = []
    for i in range(m-1):
        dif.append(x[i + 1] - x[i])
    print(sum(dif) if n == 1 else sum(sorted(dif)[:-(n-1)]))