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: Wrong Answer

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

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

x_list = sorted([int(x) for x in input().split()])
gap_list = sorted([x_list[i] - x_list[i - 1] for i in range(1, m)])
print(sum(gap_list[:-(n - 1)]))

Submission status: Wrong Answer

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

if N >= M:
  print(0)
else:
  x.sort()
  y = [x[i+1]-x[i] for i in range(len(x)-1)]
  y.sort()
  s = sum(y[:-(N-1)])
 
  print(s)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
if n >= m:
  print(0)
  exit()
s = set(map(int,input().split()))
l = list(s)
l.sort()
gap = []
for i in range(len(l)-1):
  gap.append(l[i+1]-l[i])
gap.sort()
print(sum(gap[:1-n]))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
l = list(map(int,input().split()))
l.sort()
gap = []
for i in range(m-1):
  gap.append(l[i+1]-l[i])
gap.sort()
print(sum(gap[:1-n]))

Submission status: Wrong Answer

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

li.sort()
base = max(li) - min(li)
cost = []

for i in range(m-1):
    tmp = li[i+1] - li[i]
    cost.append(tmp)

cost.sort()
res = sum(cost[-n+1:])

print(base - res)

Submission status: Wrong Answer

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

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

X = sorted(X)

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

A = sorted(A)
print(sum(A[:-n+1]))

Submission status: Wrong Answer

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

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

X = sorted(X)

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

A = sorted(A)
print(sum(A[:n+1]))

Submission status: Wrong Answer

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

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

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


L.sort()

print(sum(L[:-N+1]))

Submission status: Wrong Answer

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

xSort = sorted(x)

dif = [0] * (m - 1)
for i in range(m - 1):
    dif[i] = xSort[i + 1] - xSort[i]
ans = sum(dif)

if (n == 1 or m == 1):
    print(ans)
else:
    tar = len(dif) - n + 1
    difSort = sorted(dif)
    difS_2 = difSort[:tar]
    ans = sum(difS_2)
    print(ans)
'''  
    for j in range(n - 1):
        tar = j + 1
        tarInd = tar * -1
        tarVal = sorted(dif)[tarInd]
        ans -= tarVal
'''
# print(ans)
# >>>TLE
#
# n番目の要素を取得
# sorted(list)[-1] > 1番大きい
# sorted(list)[-２] > 2番大きい
'''
  import numpy as np
  difArray = np.array(dif)
  difIndex = difArray.argsort()

  for i in range(n - 1):
    tar = m - i
    maxIndex = difIndex[tar]
    maxVal = diff
'''

Submission status: Wrong Answer

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

xSort = sorted(x)

dif = [0] * (m - 1)
for i in range(m - 1):
    dif[i] = xSort[i + 1] - xSort[i]
ans = sum(dif)

if (n == 1 or m == 1):
    print(ans)
else:
    tar = len(dif) - n
    difSort = sorted(dif)
    difS_2 = difSort[:tar]
    ans = sum(difS_2)
    print(ans)
'''  
    for j in range(n - 1):
        tar = j + 1
        tarInd = tar * -1
        tarVal = sorted(dif)[tarInd]
        ans -= tarVal
'''
# print(ans)
# >>>TLE
#
# n番目の要素を取得
# sorted(list)[-1] > 1番大きい
# sorted(list)[-２] > 2番大きい
'''
  import numpy as np
  difArray = np.array(dif)
  difIndex = difArray.argsort()

  for i in range(n - 1):
    tar = m - i
    maxIndex = difIndex[tar]
    maxVal = diff
'''

Submission status: Wrong Answer

Solution code:
N,M=map(int,input().split())
X=list(map(int,input().split()))
X.sort()
if N>=M:
    print(0)
elif N==1:
    print(X[M-1]-X[0])
elif N==2:
    ans=X[1]-X[0]+X[M-1]-X[2]
    for i in range(1,M-2):
        a=X[i]-X[0]+X[M-1]-X[i+1]
        ans=min(ans,a)
    print(ans)
else:
    l=0
    r=M-1
    for i in range(N-2):
        a=X[l+1]-X[l]
        b=X[r]-X[r-1]
        if a>=b:
            l=l+1
        else:
            r=r-1
    ans=X[l+1]-X[l]+X[r]-X[l+2]
    for i in range(l+1,r):
        a=X[i]-X[l]+X[r]-X[i+1]
        ans=min(ans,a)
    print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
def main():
    N, M = map(int, input().split())
    X = [int(a) for a in input().split()]
    X.sort()
    dlist = list()
    for i in range(M-1):
        d = abs(X[i] - X[i+1])
        dlist.append(d)
    dlist.sort()
    print(sum(dlist[:len(dlist) - (N-1)]))
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:


def solve():

    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(L)
    # 遠い距離を除いた分の距離の合計
    print(sum(L[:M-N]))


if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

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

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

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

Submission status: Wrong Answer

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

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

diff.sort()
print(sum(diff[0:-(N-1)]))

Submission status: Wrong Answer

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

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

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

diff_sort = sorted(diff)


if M == 1:
    print(0)    
else:
    print(sum(diff_sort[0:N+1]))

Submission status: Wrong Answer

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

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

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

diff_sort = sorted(diff)


if M == 1:
    print(0)    
else:
    print(sum(diff_sort[0:N+1]))
print(diff_sort)

Submission status: Wrong Answer

Solution code:
import sys
from sys import stdin

n, m = map(int, stdin.readline().rstrip().split())
x = list(map(int, stdin.readline().rstrip().split()))

x.sort()
tmp = []
for i in range(1, len(x)):
    tmp.append(abs(x[i] - x[i - 1]))

tmp = sorted(tmp)
tmp.reverse()

if len(tmp) <= n:
    print(0)
else:
    print(sum(tmp[n-1:]))

Submission status: Wrong Answer

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

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

  dis=0
  for i in range(n-1):
    dis+=dises[i]

  ans=x[m-1]-x[0]-dis
  print(ans)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

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

X.sort()
D = [[abs(X[i] - X[i + 1]), i] for i in range(0, M - 1)]
D.sort(reverse=True)

ans = 0
if N == 1:
    for d, _ in D:
        ans += d
    print(ans)
    exit(0)

P = [False for _ in range(M)]
for d, ip in D:
    # 最後尾
    if ip == M - 2:
        N -= 1
        if (N < 0):
            break
        P[ip + 1] = True
        N -= 1
        if (N < 0):
            break
        P[ip] = True
    # 最後尾ではなく False & False の場合
    elif not (P[ip] or P[ip + 1]):
        N -= 1
        if (N < 0):
            break
        P[ip] = True
        N -= 1
        if (N < 0):
            break
        P[ip + 1] = True
    # 最後尾ではなく True & False の場合
    elif P[ip] and not P[ip + 1]:
        N -= 1
        if (N < 0):
            break
        P[ip + 1] = True
    # 最後尾ではなく False & True の場合
    elif not P[ip] and P[ip + 1]:
        N -= 1
        if (N < 0):
            break
        P[ip] = True
    # True & True の場合
    else:
        if sum(P) == M:
            print(0)
            exit(0)

ans = 0
s = 0

if not P[0]:
    # 最初のコマが存在する地点を探し、そこまでの距離を計算する
    for i in range(1, M):
        ans += X[i] - X[i - 1]
        if P[i]:
            s = i
            break

while s < M - 1:
    if (P[s] and not P[s + 1]) or (not P[s] and not P[s + 1]):
        ans += X[s + 1] - X[s]
    s += 1

print(ans)

Submission status: Wrong Answer

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

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

X.sort()
D = [[abs(X[i] - X[i + 1]), i] for i in range(0, M - 1)]
D.sort(reverse=True)

P = [False for _ in range(M)]
for d, ip in D:
    # 最後尾
    if ip == M - 2:
        N -= 1
        if (N < 0):
            break
        P[ip + 1] = True
        N -= 1
        if (N < 0):
            break
        P[ip] = True
    # 最後尾ではなく False & False の場合
    elif not (P[ip] or P[ip + 1]):
        N -= 1
        if (N < 0):
            break
        P[ip] = True
        N -= 1
        if (N < 0):
            break
        P[ip + 1] = True
    # 最後尾ではなく True & False の場合
    elif P[ip] and not P[ip + 1]:
        N -= 1
        if (N < 0):
            break
        P[ip + 1] = True
    # 最後尾ではなく False & True の場合
    elif not P[ip] and P[ip + 1]:
        N -= 1
        if (N < 0):
            break
        P[ip] = True
    # True & True の場合
    else:
        if sum(P) == M:
            print(0)
            exit(0)

ans = 0
s = 0

if not P[0]:
    # 最初のコマが存在する地点を探し、そこまでの距離を計算する
    for i in range(1, M):
        ans += X[i] - X[i - 1]
        if P[i]:
            s = i
            break

while s < M - 1:
    if (P[s] and not P[s + 1]) or (not P[s] and not P[s + 1]):
        ans += X[s + 1] - X[s]
    s += 1

print(ans)

Submission status: Wrong Answer

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

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

X.sort()
D = [[abs(X[i] - X[i + 1]), i] for i in range(0, M - 1)]
D.sort(reverse=True)
P = [False for _ in range(M)]
for d, ip in D:
    N -= 1
    if (N < 0):
        break
    if ip == M - 2:
        P[ip + 1] = True
    else:
        P[ip] = True
    N -= 1
    if (N < 0):
        break
    if ip == M - 2:
        P[ip] = True
    else:
        P[ip + 1] = True

ans = 0
s = 0 if not P[0] else 1
while s < M - 1:
    if not (P[s] and P[s + 1]):
        ans += X[s + 1] - X[s]
    s += 1
if (not P[-2]) and P[-1]:
    ans -= X[-1] - X[-2]
print(X)
print(P)
print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
N,M = map(int,input().split())
ary1 = map(int,input().split())
ary2 = sorted(list(ary1))
ary3 = ary2[1:]
ary4 = ary2[:-1]
d1  = ary2[M-1]-ary2[0]
dist1 = sorted([i-j for i,j in zip(ary3,ary4)])[M-N:M]
d2 =  sum(dist1)
print(d1-d2)

Submission status: Wrong Answer

Solution code:
import itertools
N,M = map(int,input().split())
ary1 = map(int,input().split())
ary2 = sorted(list(ary1))
#print(list(itertools.combinations(range(1,M),N)))
if N>=M:
  print(0)
elif N==1:
  print(ary2[-1]-ary2[0])
else :
  iter1 = itertools.combinations(range(1,M),N)
  ans = 2*10**5+1
  dist = [2*10**5+1]*N
  for nlist1 in itertools.combinations(range(1,M),N-1):
    nlist2 = [0] + list(nlist1)  +[M]
    print(nlist2)
    for i in range(N):
      dist[i] = ary2[nlist2[i+1]-1] - ary2[nlist2[i]]
    dist_sum = sum(dist)
    if dist_sum < ans:
      ans = dist_sum
  print(ans)

Submission status: Wrong Answer

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

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

dif.sort()
print(sum(dif[:m-n]))

Submission status: Wrong Answer

Solution code:
# from math import factorial,sqrt,ceil
# from itertools import permutations as permus
# from fractions import gcd
# from collections import deque,Counter
# from decimal import Decimal, getcontext
# # getcontext().prec = 1000
# # eps = Decimal(10) ** (-100)

import numpy as np
# from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
# from scipy.sparse import csr_matrix

# strlist = "abcdefghijklmnopqrstuvwxyz"
n,m = map(int,input().split())
# arrX = list(map(int,input().split()))
X = np.array(input().split(),dtype=np.int64)

X.sort()
X = np.diff(X)
X.sort()

if n>=m:
    ans = 0
else:
    ans = X[:-(n-1)].sum()

print(ans)
# print(*ans)   # unpackして出力。間にスペースが入る
# for row in board:
#     print(*row,sep="")    #unpackして間にスペース入れずに出力する
# print("{:.10f}".format(ans))
# print("{:0=10d}".format(ans))

Submission status: Wrong Answer

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


def kansu(N,M,X):

    x_abs = [X[m+1] -X[m] for m in range(M-1)]    
#    print(x_abs)
    cnt_n = N
    
    while cnt_n-1 > 0:
        x_abs[x_abs.index(max(x_abs))]  = -1
        cnt_n -= 1

    koma_max = 0
    sum = 0
    for m in range(M-1):
        if x_abs[m] == -1:
            sum =0
            continue
        else:
            sum += x_abs[m]
        if koma_max < sum:
            koma_max =sum
    print(koma_max)



    
    

    


N,M,X = nyu()
#print(X)

if M == 1:
    print(0)
else:
    kansu(N,M,X)

#print(S)

Submission status: Wrong Answer

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

if m <= n:
    print(0)
else:
    x.sort()
    diff = []#i番目とi+1番目の距離
    for i in range(m-1):
        diff.append(x[i+1] - x[i])
    diff.sort(reverse=True)
    # print(diff)
    for i in range(m-1-(n+1)):
        diff.pop(0)
    # print(diff)
    print(sum(diff))

Submission status: Wrong Answer

Solution code:
import heapq
n,m = map(int,input().split())
xlist = sorted(list(map(int,input().split())))
dlist = []
for i in range(m-1):
  heapq.heappush(dlist,-xlist[i+1]+xlist[i])

for i in range(m-n-2):
  heapq.heappop(dlist)

print(-sum(dlist))

Submission status: Wrong Answer

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()

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

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

X.sort()

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

dist.sort()

print(sum(dist[:len(dist)-(N-1)]))

Submission status: Wrong Answer

Solution code:
import itertools
a=0;b=0;m=0;l=0
N,M=map(int,input().split())
X=list(map(int,input().split()))
l=M-N; m=sum(X)
if N>=M:
  print(0)
else:
  for i in itertools.combinations(X,l):
    L=sorted(list(map(int,i)))
    print(L)
    for j in range(1,l):
      a=a+(L[j]-L[j-1])
    print(a)
    if a<m:
      m=a
    a=0
  print(m)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
x = sorted(list(map(int, input().split())))
l = []
for i in range(m-1):
    l.append(abs(x[i]-x[i+1]))
l = sorted(l)
print(sum(l[:-n+1]))

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

_NUMINT_ALL = list(range(10))


def main():
    ans = solve()
    if ans is not None:
        print(ans)


def solve():
    N, M = iip(False)
    X = iip()
    X.sort()

    A = [X[i+1] - X[i] for i in range(len(X)-1)]
    A.sort()

    return sum(A[:min(0, -N+1)])


#####################################################ライブラリ集ここから

def iip(listed=True, num_only=True):  # 数字のinputをlistで受け取る
    if num_only:
        ret = [int(i) for i in input().split()]
    else:
        ret = [int(i) if i in _NUMINT_ALL else i for i in input().split()]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def iipt(l, listed=False, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed, num_only=num_only))
    return ret


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

_NUMINT_ALL = list(range(10))


def main():
    ans = solve()
    if ans is not None:
        print(ans)


def solve():
    N, M = iip(False)
    X = iip()
    X.sort()

    if N >= M:
        return 0

    A = [X[i+1] - X[i] for i in range(len(X)-1)]
    A.sort()

    return sum(A[:min(0, -N+1)])


#####################################################ライブラリ集ここから

def iip(listed=True, num_only=True):  # 数字のinputをlistで受け取る
    if num_only:
        ret = [int(i) for i in input().split()]
    else:
        ret = [int(i) if i in _NUMINT_ALL else i for i in input().split()]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def iipt(l, listed=False, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed, num_only=num_only))
    return ret


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
mod = 10 ** 9 + 7
mod2 = 2 ** 61 + 1
from collections import deque
import heapq
from bisect import bisect_left, insort_left, bisect_right

_NUMINT_ALL = list(range(10))


def main():
    ans = solve()
    if ans is not None:
        print(ans)


def solve():
    N, M = iip(False)
    X = iip()
    X.sort()

    if N >= M:
        return 0

    A = [X[i+1] - X[i] for i in range(len(X)-1)]
    A.sort()

    return sum(A[:max(0, -N+1)])


#####################################################ライブラリ集ここから

def iip(listed=True, num_only=True):  # 数字のinputをlistで受け取る
    if num_only:
        ret = [int(i) for i in input().split()]
    else:
        ret = [int(i) if i in _NUMINT_ALL else i for i in input().split()]

    if len(ret) == 1 and not listed:
        return ret[0]
    return ret


def saidai_kouyakusuu(A):  # 最大公約数
    l = len(A)
    while True:
        m = min(A)
        mx = max(A)
        if m == mx:
            return m

        for i in range(l):
            if A[i] % m == 0:
                A[i] = m
            else:
                A[i] %= m


def sort_tuples(l, index):  # タプルのリストを特定のインデックスでソートする
    if isinstance(l, list):
        l.sort(key=lambda x: x[index])
        return l
    else:
        l = list(l)
        return sorted(l, key=lambda x: x[index])


def count_elements(l):  # リストの中身の個数を種類分けして辞書で返す
    d = {}
    for i in l:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return d


def safeget(l, index, default="exception"):  # listの中身を取り出す時、listからはみ出たり
    if index >= len(l):                      # マイナスインデックスになったりするのを防ぐ
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。配列の長さは", len(l), "です"]))
        else:
            return default
    elif index < 0:
        if default == "exception":
            raise Exception("".join(["safegetに不正な値 ", index, "が渡されました。負の値は許可されていません"]))
        else:
            return default
    else:
        return l[index]


def iipt(l, listed=False, num_only=True):  # 縦向きに並んでいるデータをリストに落とし込む(iip利用)
    ret = []
    for i in range(l):
        ret.append(iip(listed=listed, num_only=num_only))
    return ret


def sortstr(s):  # 文字列をソートする
    return "".join(sorted(s))


def iip_ord(startcode="a"):  # 文字列を数字の列に変換する(数字と文字は1:1対応)
    if isinstance(startcode, str):
        startcode = ord(startcode)
    return [ord(i) - startcode for i in input()]


def YesNo(s):  # TrueFalseや1, 0をYesNoに変換する
    if s:
        print("Yes")
    else:
        print("No")


def fprint(s):  # リストを平たくしてprintする(二次元リストを見やすくしたりとか)
    for i in s:
        print(i)


def bitall(N):  # ビット全探索用のインデックスを出力
    ret = []
    for i in range(2 ** N):
        a = []
        for j in range(N):
            a.append(i % 2)
            i //= 2
        ret.append(a)
    return ret

def split_print_space(s):  # リストの中身をスペース区切りで出力する
    print(" ".join([str(i) for i in s]))


def split_print_enter(s):  # リストの中身を改行区切りで出力する
    print("\n".join([str(i) for i in s]))


def soinsuu_bunkai(n):  # 素因数分解
    ret = []
    for i in range(2, int(n ** 0.5) + 1):
        while n % i == 0:
            n //= i
            ret.append(i)
        if i > n:
            break
    if n != 1:
        ret.append(n)
    return ret


def conbination(n, r, mod, test=False):  # nCrをmodを使って計算する
    if n <= 0:
        return 0
    if r == 0:
        return 1
    if r < 0:
        return 0
    if r == 1:
        return n
    ret = 1
    for i in range(n - r + 1, n + 1):
        ret *= i
        ret = ret % mod

    bunbo = 1
    for i in range(1, r + 1):
        bunbo *= i
        bunbo = bunbo % mod

    ret = (ret * inv(bunbo, mod)) % mod
    if test:
        # print(f"{n}C{r} = {ret}")
        pass
    return ret


def inv(n, mod):  #  modnにおける逆元を計算
    return power(n, mod - 2)


def power(n, p, mod_=mod):  # 繰り返し二乗法でn**p % modを計算
    if p == 0:
        return 1
    if p % 2 == 0:
        return (power(n, p // 2, mod_) ** 2) % mod_
    if p % 2 == 1:
        return (n * power(n, p - 1, mod_)) % mod_


if __name__ == "__main__":
    main()