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: Time Limit Exceeded

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

X=[int(_) for _ in input().split()]
X.sort()
if N>=M:
    print('0')
    exit(0)

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

Sum.sort()
for i in range(N-1):
    Sum.remove(Sum[-1])

print(sum(Sum))

Submission status: Time Limit Exceeded

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


Xs.sort()
costs=[]

for i in range(M-1):
    costs.append(abs(int(Xs[i])-int(Xs[i+1])))

for i in range(N-1):
    if not costs:
        print(0)
        exit(0)
    costs.remove(max(costs))




print(sum(costs))

Submission status: Time Limit Exceeded

Solution code:
import sys

koma_num, goal_num = [int(a) for a in input().split(' ')]

if koma_num >= goal_num:
  print(0)
  sys.exit()

goals = [int(a) for a in input().split(' ')]
goals.sort()
dist_diff = [int(goals[i+1] - goals[i]) for i in range(len(goals)-1)]

for i in range(koma_num-1):
  max_dist = max(dist_diff)
  dist_diff.remove(max_dist)

print(sum(dist_diff))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

X = sorted(X)
l = []

if len(X) <= N:
	print(0)

else:
	for n in range(len(X)):
		if n != 0:
			l.append(abs(X[n - 1] - X[n]))

	ans = 0
	for i in range(M - N):
		ans += l.pop(np.argmin(l))

	print(ans)

Submission status: Time Limit Exceeded

Solution code:
n,m =(int(i) for i in input().split())
x = list(int(i) for i in input().split())
x.sort()
sa = []
ans = 0
if m <= n:
  print('0')
  exit()
for i in range(m-1):
  sa.append(x[i+1]-x[i])
for i in range(n-1):
  tmp1 = max(sa)
  sa.remove(tmp1)

ans = sum(sa)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def aa(l):
  a = []
  b = 0
  for i in l:
    if i == 0:
      a.append(b)
    else:
      b += i
  a.append(b)
  return a

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

s = sorted(x)
ss = [0]+[s[i+1] - s[i] for i in range(m-1)]

for i in range(n-1):
  ss[ss.index(max(ss))] = 0

print(max(aa(ss)))

Submission status: Time Limit Exceeded

Solution code:
n,m=list(map(int,input().split()))
l=list(map(int,input().split()))
l.sort()
d=[]
for i in range(0,m-1):
    d.append(l[i+1] - l[i])
try:
    for i in range(0,n-1):
        d.sort()
        ld=len(d)
        d.pop(ld-1)
    print(sum(d))
except IndexError:
    print(0)

Submission status: Time Limit Exceeded

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

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

X.sort();

dif = [X[i+1]-X[i] for i in range(M-1)]
if M==1:
    dif = [0]
ans = sum(dif)
for i in range(N-1):
    ans -= max(dif)
    dif[dif.index(max(dif))] = 0

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().split())
xl = [int(i) for i in input().split()]
xl.sort()
d = m - n
if d <= 0:
    print(0)
else:
    dl = []
    for i in range(len(xl)-1):
        dl.append(xl[i+1] - xl[i])
        dl.sort()
    print(sum(dl[:d]))

Submission status: Time Limit Exceeded

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

if n == 1:
    print(max(x) - min(x))
elif n >= m:
    print(0)
else:

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

    for i in range(n - 1):
        dif.remove(max(dif))
    print(sum(dif))

Submission status: Time Limit Exceeded

Solution code:
import itertools
n,m = map(int,input().split())
zahyou_list = [i for i in map(int,input().split())]
zahyou_list.sort()
#print(zahyou_list)
kaisa_list = []
#print(sum(kaisa_list))

for i in range(len(zahyou_list)-1):
    kaisa_list.append(zahyou_list[i+1] - zahyou_list[i])
mini = sum(kaisa_list)
#print(kaisa_list)
if n >= m:
    print(0)
else:
    for v in itertools.combinations(kaisa_list,n-1):
        #print(mini)
        #print(sum(kaisa_list)-sum(v))
        mini = min(mini,sum(kaisa_list)-sum(v))
    print(mini)
"""
階差のリストのうちn-1個要素を減らして合計値の最小値で求める
"""

Submission status: Time Limit Exceeded

Solution code:


import sys
import math

# -*- coding: utf-8 -*-

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

a=list(map(int, input().split()))
##まずソート
a.sort()

dist = []
##次のターゲットとの距離を出す
for i in range(m-1):
    dist.append((a[i+1]-a[i]))

##最後のターゲットは右隣がないので大きな値
dist.append(1000000)

dist.sort()
score = 0
##隣との距離が小さい順に駒に回らせる
while len(dist) > n :
    score += dist[0]
    dist = dist[1:]

print(score)

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
y=[]
for i in range(1,m):
    y.append(x[i]-x[i-1])
for j in range(n-1):
    if len(y)!=0:
        y.pop(y.index(max(y)))
print(sum(y))

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり


N,M = MI()
X = LI()

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

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

Submission status: Accepted

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

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)
    exit()
Xs = sorted(X)
dst = []
for i in range(M-1):
    dst.append(Xs[i+1] - Xs[i])
#print(Xs)
#print(dst)
dsts = sorted(dst)
#print(dsts[:len(dsts)-N+1])
print(sum(dsts[:len(dsts)-N+1]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,M  = map(int,input().split())
N_List = sorted(list(map(int,input().split())))
N_Diff =[]
for i in range(1,M):
    N_Diff.append(N_List[i]-N_List[i-1])
if N >= M:
    ans = 0
elif M == 1:
    ans = sum(N_Diff)
else:
    ans = sum(sorted(N_Diff)[:M-N])
print(ans)

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
if n >= m :
  print(0)
else:
  ls=[int(s) for s in input().split()]
  ls.sort()
  d=[ls[i+1]-ls[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=[int(i) for i in input().split()]

x_list.sort()

differ_list=[]

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
N,M=map(int,input().split())
L=list(map(int,input().split()))
if N>=M:
    print(0)
    sys.exit()
L.sort()
K=[]
s=0
for i in range(M-1):
    K.append(L[i+1]-L[i])
K.sort(reverse=True)
for i in range(N-1):
    s+=K[i]
print(L[M-1]-L[0]-s)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
a = sorted(list(map(int,input().split())))
dst = [0]*(m-1)
for i in range(m-1):
  dst[i] = abs(a[i+1]-a[i])
dst.sort(reverse=True)
print(sum(dst[n-1::]))

Submission status: Accepted

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

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

Submission status: Accepted

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

    if m <= n:
        print(0)
        return

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

    d.sort()

    print(sum(d[0:(m-n)]))
    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

dif.sort()
difLen = len(dif)
# M - N = (M-1) - (N-1)
e = M - N
if e < 0:
	print(0)
	exit()
ans = sum(dif[0:e])

print(ans)

Submission status: Accepted

Solution code:
n, m = map(int, input().split())
X = sorted(set(list(map(int, input().split()))))
s = []
for i in range(m-1):
    s.append(X[i+1] - X[i])
s = sorted(s)[::-1]

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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 = sorted(dif)[::-1]
print(sum(dif[n-1:]))

Submission status: Accepted

Solution code:
def main():
    # n = int(input())
    n, m = map(int, input().split())
    x = list(map(int, input().split()))
    # s = input()
    # h = [int(input()) for _ in range(n)]

    x.sort()

    subs = []

    for i in range(1, m):
        subs.append(abs(x[i]-x[i-1]))

    subs.sort()
    if (m < n):
        print(0)
    else:
        print(sum(subs[0:m-n]))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import tee


def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


N, M, *X = map(int, open(0).read().split())
if N >= M:
    print(0)
    exit()

X.sort()
diffs = [cur - prev for prev, cur in pairwise(X)]
diffs.sort()
print(sum(diffs[: M - N]))

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush
from bisect import bisect_left,bisect_right 
import sys,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))

n,m = inpl()
a = inpl()
a.sort()
b = []
for i in range(m-1):
    b.append(a[i+1]-a[i])
b.sort(reverse = True)
print(sum(b[n-1:]))

Submission status: Accepted

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

D = [r - l for l, r in zip(X, X[1:])]
D.sort()

ans = sum(D)
while D and N > 1:
    N -= 1
    ans -= D.pop()
print(ans)

Submission status: Accepted

Solution code:
from collections import deque,defaultdict,Counter
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from bisect import bisect_left,bisect_right
from math import sqrt,gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode
import sys
sys.setrecursionlimit(10 ** 6)

INF = float('inf')

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse=False):
    data.sort(key=lambda x:x[col],reverse=revese)
    return data

def mymax(data):
    M = -1*float('inf')
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float('inf')
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def mydictvaluesort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[1] )

def mydictkeysort(dictionary):
    return sorted( dictionary.items(), key=lambda x:x[0] )

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(' ')
        elif type(ls[0])==str:
            print(' '.join(ls))
        elif type(ls[0])==int:
            print(' '.join(map(str,ls)))
        else:
            print('Output Error')
    else:
        if len(ls)==0:
            print('')
        elif type(ls[0])==str:
            print(''.join(ls))
        elif type(ls[0])==int:
            print(''.join(map(str,ls)))
        else:
            print('Output Error')

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input()) for _ in range(n) ]

# ddict = defaultdict(lambda: 0)
# ddict = defaultdict(lambda: 1)
# ddict = defaultdict(lambda: int())
# ddict = defaultdict(lambda: list())
# ddict = defaultdict(lambda: float())

mod = 10**9 + 7

n,m = MI()
x = RI()

x.sort()
# print(x)
ls = []
for i in range(m-1):
    ls.append( x[i+1] - x[i] )
# print(ls)
ls.sort()
if n==1:
    pass
else:
    ls = ls[:-1*(n-1)]
ans = sum(ls)
print(ans)

Submission status: Accepted

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

diff = [0]*(m-1)

for i in range(m-1):
    diff[i] = xl[i+1] - xl[i]

diff_s = sorted(diff, reverse=True)
# print(diff_s)
print(sum(diff_s[n-1:]))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

X.sort()
Y = []
for i in range(m-1):
    y = X[i+1]-X[i]
    Y.append(y)
Y.sort()
#print(Y)
ans = sum(Y[0:m-(n-1)-1])
print(ans)

Submission status: Accepted

Solution code:
n, m, *a = map(int, open(0).read().split())
a.sort()
b = []
for i in range(m - 1):
    b.append(a[i + 1] - a[i])
b.sort()
ans = 0
for i in range(m - n):
    ans += b[i]
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,m = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
t = 0
s = []
for i in range(m-1):
    t += x[i+1]-x[i]
    s.append(x[i+1]-x[i])
s.sort(reverse = True)
for i in range(min(n-1,m-1)):
    t -= s[i]
print(t)

Submission status: Accepted

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

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

yy = [abs(xx[i]-xx[i+1]) for i in range(m-1)]

sy = sorted(yy)

if n > 1:
  print(sum(sy[:-n+1]))
else:
  print(xx[-1] - xx[0])

Submission status: Accepted

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

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

x_sorted = sorted(x)
dx = [abs(x_sorted[i+1]-x_sorted[i]) for i in range(m-1)]
dx_sorted = sorted(dx,reverse=True)

result = sum(dx_sorted)
for i in range(n-1):
  result -= dx_sorted[i]
print(result)

Submission status: Accepted

Solution code:
def mapt(fn, *args):
    return tuple(map(fn, *args))


def Input():
    return mapt(int, input().split(" "))


def main():
    n, m = Input()
    x = sorted(Input())

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


main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 18:32:27 2020

@author: liang
"""
"""
配列のスライス
X[0:-(N-1)]などで切ると、N=1の時にバグるので注意
X[0:len(X) - (N-1)]のように要素数-後ろから数えたindexとする

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

def solve():
    if N >= M :
        return 0
    X.sort()
    d = [X[i+1] - X[i] for i in range(M-1)]
    d.sort()
    #print(X)
    #print(d)
    return sum(d[0:M-N])
print(solve())

Submission status: Accepted

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

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

x.sort()

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())
al = list(map(int, input().split()))

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

al_s = sorted(al)
res=[]
for i in range(m-1):
    res.append(al_s[i+1]-al_s[i])

res_s = sorted(res)

print(sum(res)-sum(res_s[m-n:]))

Submission status: Accepted

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

if n>=m:
  print(0)
else:
  num=n-1
  sl=sorted(l)

  dsl=[abs(sl[i+1]-sl[i]) for i in range(m-1)]

  dsl=sorted(dsl)
  print(sum(dsl[0:len(dsl)-num]))

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:
    diff=[X[i+1]-X[i] for i in range(M-1)]
    diff.sort()
    print(sum(diff[0:M-N]))

Submission status: Accepted

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

dist = []
for i in range(m-1):
    dist.append(X[i+1]-X[i])
dist.sort()
    
ans = 0
for i in range(max(m-n,0)):
    ans += dist[i]

print(ans)

Submission status: Accepted

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

l.sort()
# print(l)
list=[]
if n < m:
    for i in range(m - 1):
        list.append(abs(l[i + 1] - l[i]))

    list.sort()
    # print(list)
    print(sum(list[0:(m - n)]))
else:
    print(0)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import math
import decimal
import itertools
from itertools import product
from functools import reduce


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

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

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

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


def input():
    return sys.stdin.readline()[:-1]


def gcd(*numbers):
    return reduce(math.gcd, numbers)


def lcm_base(x, y):
    return (x * y) // math.gcd(x, y)


def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)


def sort_zip(a: list, b: list):
    z = zip(a, b)
    z = sorted(z)
    a, b = zip(*z)
    a = list(a)
    b = list(b)
    return a, b


if __name__ == '__main__':
    main()

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import numpy as np
N, M = map(int, input().split())
X = list(map(int, input().split()))
sortX = np.array(sorted(X), dtype=np.int64)
diffX = np.sort(np.diff(sortX))
if N == 1:
    print(np.sum(diffX))
    exit()
ans = np.sum(diffX[:-(N-1)])
print(ans)

Submission status: Accepted

Solution code:
N, M = map(int, input().split())
X = list(map(int, input().split()))
sortX = sorted(X)
diffX = [sortX[i] - sortX[i-1] for i in range(1, M)]
sdiffX = sorted(diffX)
if N == 1:
    print(sum(sdiffX))
    exit()
ans = sum(sdiffX[:-(N-1)])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# import sys
# sys.setrecursionlimit(10 ** 6)
# import bisect
# from collections import deque
# from decorator import stop_watch
# 
# 
# @stop_watch
def solve(N, M, Xi):
    lengthes = []
    Xi.sort()
    for i in range(1, M):
        lengthes.append(abs(Xi[i - 1] - Xi[i]))
    lengthes.sort()
    num = N if N < M else M
    print(sum(lengthes[:M - num]))


if __name__ == '__main__':
    # S = input()
    # N = int(input())
    N, M = map(int, input().split())
    Xi = [int(i) for i in input().split()]
    # Bi = [int(i) for i in input().split()]
    # ABi = [[int(i) for i in input().split()] for _ in range(N)]
    solve(N, M, Xi)

    # # test
    # from random import randint
    # from func import random_str
    # solve()

Submission status: Accepted

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

gaps = [x[i] - x[i-1] for i in range(1, len(x))]

if n == 1:
    print(sum(gaps))
else:
    print(sum(sorted(gaps)[:-n+1]))

Submission status: Accepted

Solution code:
n, m = map(int,input().split())
x = list(map(int,input().split()))
ans = 0
if n<m:
    x.sort()
    l = [x[i+1]-x[i] for i in range(m-1)]
    l.sort()
    ans = max(x)-min(x)
    for i in range(n-1):
        ans -= l[-1-i]
print(ans)

Submission status: Accepted

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
if n>=m:
  print(0)
  exit()
data=[0]*(m-1)
for i in range(m-1):
  data[i]=x[i+1]-x[i]
data.sort()
res=0
for i in range(n-1):
  res+=data[m-2-i]
print(sum(data)-res)

Submission status: Accepted

Solution code:
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right #func(リスト,値)
from heapq import heapify, heappop, heappush
from math import *

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)

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

Submission status: Accepted

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

delta = []
for i in range(m-1):
    delta.append(abs(xl[i]-xl[i+1]))
delta.sort(reverse=True)
print(sum(delta[n-1:]))

Submission status: Accepted

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

print(X[M-1]-X[0]+1-ans-N)

Submission status: Accepted

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

Submission status: Accepted

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

X.sort()

subs = []
for i in range(M-1):
    subs.append(X[i+1]-X[i])
subs.sort()
if N == 1:
    print(sum(subs))
    exit()
print(sum(subs[:-(N-1)]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import numpy as np

def main():
    N, M = map(int, input().split())
    if N >= M:
        print(0)
        exit()
    X = sorted(list(map(int, input().split())))
    if N == 1:
        print(X[-1] - X[0])
        exit()
    D = np.array([X[i+1] - X[i] for i in range(M-1)])
    idx_list = np.argsort(-D)[:N-1]
    ans = sum(D)
    for idx in idx_list:
        ans -= D[idx]
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return input().rstrip().decode()
def II(): return int(input())
def FI(): return float(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()



def main():
	n,m=MI()
	x=LI()
	x.sort()
	A=[]
	for i,j in zip(x[1:],x[:-1]):
		A.append(i-j)
	#print(A)
	A.sort()
	print(sum(A[:max(m-n,0)]))


if __name__ == "__main__":
	main()

Submission status: Accepted

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

li_X.sort()
li_X_delta = []
for i in range(len(li_X)-1):
    li_X_delta.append(li_X[i+1]-li_X[i])
li_X_delta.sort(reverse=True)
cnt = 0

ans = li_X[-1] - li_X[0]
for i in range(min(n-1, len(li_X_delta))):
    ans -= li_X_delta[i]
print(ans)

Submission status: Accepted

Solution code:
#40 C - Streamline
N,M = map(int,input().split())
X = list(map(int,input().split()))
X = sorted(X,reverse = False)

# 区間の距離のリスト
if len(X) == 1:
    print(0)
else:
    dist = []
    for i in range(1,M):
        dist.append(X[i]-X[i-1])
    dist = sorted(dist,reverse = False)
    # 区間の距離を降順に N-1 個分消去
    for k in range(N-1):
        dist.pop()
        if len(dist) == 0:
            break
    print(sum(dist))

Submission status: Accepted

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
  return int(readline())
n,m = readInts()
A = sorted(readInts())
if n >= m:
    print(0)
else:
    dist = []
    all = 0
    for i in range(m-1):
        dist.append(A[i+1] - A[i])
        all += A[i+1] - A[i]
    dist = sorted(dist, reverse = True)
    print(all - sum(dist[:n-1]))

Submission status: Accepted

Solution code:
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()
if M-N >= 0:
  print(sum(d[0:M-N]))
else:
  print(0)

Submission status: Accepted

Solution code:
from itertools import accumulate
import sys


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


N, M = LI()
X = LI()
if M <= N:
    print(0)
    sys.exit()
sa = []
X.sort()
for i in range(M-1):
    sa.append(X[i+1]-X[i])
sa.sort(reverse=True)
sa = list(accumulate(sa))
if N == 1:
    print(sa[M-2])
else:
    print(sa[M-2]-sa[N-2])

Submission status: Accepted

Solution code:
n, m, *a = map(int, open(0).read().split())
a.sort()
print(sum(sorted([a[i + 1] - a[i] for i in range(m - 1)])[:max(0, m - n)]))

Submission status: Accepted

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

Submission status: Accepted

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

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

X.sort()

if n == 1:
    print(X[-1]-X[0])
    exit()

Y = []
for i in range(m-1):
    Y.append(X[i+1]-X[i])
#print(Y)
Y.sort()
ans = sum(Y[0:-(n-1)])
print(ans)