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: Runtime Error

Solution code:
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb  # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
# If the element is already present in the list,

# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect

# If the element is already present in the list,
# the right most position where element has to be inserted is returned

# ==============================================================================================
# fast I/O region

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None


    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType


def iterative(f, stack=[]):
    def wrapped_func(*args, **kwargs):
        if stack: return f(*args, **kwargs)
        to = f(*args, **kwargs)
        while True:
            if type(to) is GeneratorType:
                stack.append(to)
                to = next(to)
                continue
            stack.pop()
            if not stack: break
            to = stack[-1].send(to)
        return to

    return wrapped_func


#### END ITERATE RECURSION ####

# ===============================================================================================
# some shortcuts

mod = 1000000007


def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def out(var): sys.stdout.write(str(var))  # for fast output, always take string

def lis(): return list(map(int, inp().split()))

def stringlis(): return list(map(str, inp().split()))

def sep(): return map(int, inp().split())

def strsep(): return map(str, inp().split())


def zerolist(n): return [0] * n

def nextline(): out("\n")  # as stdout.write always print sring.

def testcase(t):
    for p in range(t):
        solve()

def printlist(a):
    for p in range(0, len(a)):
        out(str(a[p]) + ' ')


def solve():
    n,m=sep()
    ar=lis()
    ar.sort()
    temp=[]
    for i in range(1,n):
        temp.append(ar[i]-ar[i-1])
    if n>=m:
        print(0)
    else:
        print(sum(temp[:m-n]))
    
    
    
solve()

Submission status: Runtime Error

Solution code:
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb  # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
# If the element is already present in the list,

# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect

# If the element is already present in the list,
# the right most position where element has to be inserted is returned

# ==============================================================================================
# fast I/O region

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None


    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType


def iterative(f, stack=[]):
    def wrapped_func(*args, **kwargs):
        if stack: return f(*args, **kwargs)
        to = f(*args, **kwargs)
        while True:
            if type(to) is GeneratorType:
                stack.append(to)
                to = next(to)
                continue
            stack.pop()
            if not stack: break
            to = stack[-1].send(to)
        return to

    return wrapped_func


#### END ITERATE RECURSION ####

# ===============================================================================================
# some shortcuts

mod = 1000000007


def inp(): return sys.stdin.readline().rstrip("\r\n")  # for fast input

def out(var): sys.stdout.write(str(var))  # for fast output, always take string

def lis(): return list(map(int, inp().split()))

def stringlis(): return list(map(str, inp().split()))

def sep(): return map(int, inp().split())

def strsep(): return map(str, inp().split())


def zerolist(n): return [0] * n

def nextline(): out("\n")  # as stdout.write always print sring.

def testcase(t):
    for p in range(t):
        solve()

def printlist(a):
    for p in range(0, len(a)):
        out(str(a[p]) + ' ')


def solve():
    n,m=sep()
    ar=lis()
    ar.sort()
    temp=[]
    for i in range(1,n):
        temp.append(ar[i]-ar[i-1])
    if n>=m:
        print(0)
    else:
        print(sum(temp[:m-n])
    
    
    
solve()

Submission status: Runtime Error

Solution code:


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

X.sort()
cnt = 0
arr = [0]*(M-1)
if N > M:
    ans = 0
else:
    for i in range(1,M):
        arr[i] = (abs(X[i-1]-X[i]))
    #print(arr)
    arr.sort()
    ans = sum(arr[0:M-N])
print(ans)

Submission status: Runtime Error

Solution code:
import math
from math import gcd
INF = float("inf")

import sys
input=sys.stdin.readline
sys.setrecursionlimit(500*500)
import itertools
from collections import Counter,deque

def main():
    n,m = map(int, input().split())
    l = list(map(int, input().split()))
    l.sort()

    ans = 0
    if n<m:
        L = []
        for i in range(m-1):
            l.append(l[i+1] - l[i])
        L.sort()
        for i in range(m-n):
            ans += L[i]
    print(ans)


if __name__=="__main__":
    main(
    )

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
x = list(map(int,input().split()))
t_3 = max(x) - min(x)
t = []
t_2 = 0
x.sort()
if m == 1:
    print(0)
    exit()

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

t.sort(reverse=True)
for i in range(n-1):
    t_2 += t[i]

print(t_3-t_2)

Submission status: Runtime Error

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

if m==1 :
    print(0)
    exit()

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

D.sort(reverse=True)
d=0
if i>1:
    for i in range(n-1):
        d += D[i]    

ans = sum(D)-d
print(ans)

Submission status: Runtime Error

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

if m==1 :
    print(0)
    exit()

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

D.sort(reverse=True)
d=0
for i in range(n-1):
    d += D[i]    

ans = sum(D)-d
print(ans)

Submission status: Runtime Error

Solution code:
N,M=map(int,input().split())
if N>M:
    print(0)
lst=list(map(int,input().split()))
lst.sort()
sum_1=max(lst)-min(lst)
D=[]
for i in range(1,M):
    D.append(lst[i]-lst[i-1])
D.sort(reverse=True)
sum_2=0
for i in range(N-1):
    sum_2+=D[i]
ans=0
ans=sum_1-sum_2
print(ans)

Submission status: Runtime Error

Solution code:
N,M=map(int,input().split())
lst=list(map(int,input().split()))
lst.sort()
sum_1=max(lst)-min(lst)
D=[]
for i in range(1,M):
    D.append(lst[i]-lst[i-1])
D.sort(reverse=True)
sum_2=0
for i in range(N-1):
    sum_2+=D[i]
ans=0
ans=sum_1-sum_2
print(ans)

Submission status: Runtime Error

Solution code:
N,M=map(int,input().split())
lst=list(map(int,input().split()))
sort(lst)
sum_1=sum(lst)
D=[]
for i in range(1,M):
    D.append(lst[i]-lst[i-1])
sort(D,reverse=True)
sum_2=0
for i in range(N-1):
    sum_2+=D[i]
ans=0
ans=sum_1-sum_2
print(ans)

Submission status: Runtime Error

Solution code:
import sys

# N: コマ数
# M: 地点数

# N,M,*X = map(int, open(0).read().split())

# コマ数が地点数以上の場合、各地点にコマを配置できる
# よって 0 回の移動で目的を達成できる
if N >= M:
    print(0)
    sys.exit()

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

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

Submission status: Runtime Error

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

X.sort()

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

if len(ans) == 0:
    print(0)
    sys.exit()

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

Submission status: Runtime Error

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

X.sort()

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

if len(ans) == 0:
    print(0)
    sys.exit()

ans.sort()
for _ in range(N-1):
    ans.pop()

print(sum(ans))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
 
## Library
 
import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools
import copy
 
## input
 
# N=int(input())
# A,B,C,D=map(int, input().split())
# S = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split()) 
#    P = [list(map(int,input().split())) for i in range(M)]
#    S = []
#    for _ in range(N):
#        S.append(list(input()))
 
N,M = map(int, input().split())
X = list(map(int, input().split()))

X.sort()

ans = X[M-1] - X[0]
tmp = []

for i in range(1,M):
    tmp2 = X[i] - X[i-1]
    if len(tmp) < N-1:
        tmp.append(tmp2)
    else:
        tmp3 = min(tmp)
        if tmp3 < tmp2:
            tmp.remove(tmp3)
            tmp.append(tmp2)

print(ans - sum(tmp))

Submission status: Runtime Error

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

Submission status: Runtime Error

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

import sys

def main():
    input = sys.stdin.readline
    n,m = map(int, input().split())
    x_list = list(map(int, input().split()))
    if m == 1:
        print(0)
        exit(0)
    sabun_list = []
    x_list.sort()
    for i,x in  enumerate(x_list):
        if i == 0:
            continue
        sabun_list.append(x - x_list[i-1])
    result = 0
    sum_max_sabun = 0
    for i in range(n-1):
        max_index = sabun_list.index(max(sabun_list))
        sum_max_sabun += sabun_list[max_index]
        sabun_list.pop(max_index)
    
    result = (x_list[-1] - x_list[0]) - sum_max_sabun

    print(result)

    return


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def resolve():
    '''
    code here
    '''
    import collections
    N, M = [int(item) for item in input().split()]
    Xs = [int(item) for item in input().split()]
    if N < M-1:
        Xs.sort()
        ds = [Xs[i] - Xs[i-1] for i in range(1, M)]
        ds.sort()
        # print(ds)
        print(sum(ds[:-1*(N-1)]))
    elif M - N == 1:
        Xs.sort()
        ds = [Xs[i] - Xs[i-1] for i in range(1, M)]
        ds.sort()
        # print(ds)
        print(sum(ds[0]))
        
    else:
        print(0)


if __name__ == "__main__":
    resolve()

Submission status: Runtime Error

Solution code:
import math
import collections
import fractions
import itertools

def solve():
    n, m = map(int, input().split())
    x = list(map(int, input().split()))
    x.sort()
    if n >= m:
        print(0)
    else:
        diff = [abs(x[i] - x[i+1]) for i in range(m-1)]
        diff.sort(reverse=True)
        ans = sum(diff)
        for i in range(n-1):
            ans -= diff[i]
    print(ans)
    return 0

if __name__ == "__main__":
    solve()

Submission status: Runtime Error

Solution code:
import numpy as np
#from numba import njit

#(N, K) = map(int, input().split())
#A = np.array(list(map(int, input().split())))
(N,M) = map(int, input().split())
X = map(int, input().split())
X = sorted(X)

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

Y = sorted(Y, key=lambda x: (x[1]))
Y.reverse()

Z = []
last = 0
for i in range(0,min(N-1, len(Y))):
    Z.append(X[last:Y[i][0]])
    last = Y[i][0]
Z.append(X[last:])
if len(Z) == 0:
    Z.append(X)

s = 0
for array in Z:
    u = max(array)
    l = min(array)
    s += u - l

print(s)

Submission status: Runtime Error

Solution code:
import numpy as np
#from numba import njit

#(N, K) = map(int, input().split())
#A = np.array(list(map(int, input().split())))
(N,M) = map(int, input().split())
X = map(int, input().split())
X = sorted(X)

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

Y = sorted(Y, key=lambda x: (x[1]))
Y.reverse()

Z = []
last = 0
for i in range(0,min(N-1, len(Y))):
    Z.append(X[last:Y[i][0]])
    last = Y[i][0]
if len(Z) == 0:
    Z.append(X)

s = 0
for array in Z:
    u = max(array)
    l = min(array)
    s += u - l

print(s)

Submission status: Runtime Error

Solution code:
n,m=map(int, input().split())
x=[int(i) for i in input().split()]
x.sort()
dist = abs(x[-1]-x[0])
diff = []

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

diff.sort(key = lambda x:x[0],reverse = True)
for i in range(n-1):
    dist-=diff[i][0]
print(dist)

Submission status: Runtime Error

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7

N, M = I()
X = l()
X.sort()
kyori = []

if M == 1:
    print(0)
    sys.exit()
for i in range(len(X)-1):
    s = X[i+1]-X[i]
    kyori.append(s)

kyori.sort()
kyori.reverse()

for j in range(N-1):
    kyori.pop(0)

print(sum(kyori))

Submission status: Runtime Error

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

diff = sorted(diff, reverse=True)

dist = x[-1] - x[0]
if dist < n:
    print(0)
    exit()

for i in range(n-1):
    dist -= diff[i]

print(dist)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
def main():
    N, M = map(int, input().split())
    X = [j for j in map(int, input().split())]
    if N >= M:
        print(0)
        exit()
    X.sort()
    s = max(X)-min(X)
    d = [X[i+1]-X[i] for i in range(M-1)]
    d.sort()
    if N = 1:
        print(s-d[-1])
    else:
        print(s-sum(d[-N+1:]))


main()

Submission status: Runtime Error

Solution code:
deff main():
    N, M = map(int, input().split())
    if N >= M:
        print(0)
        exit()
    X = [j for j in map(int, input().split())]
    X.sort()
    s = max(X)-min(X)
    d = [X[i+1]-X[i] for i in range(M-1)]
    d.sort()

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

main()

Submission status: Runtime Error

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

ans=0
if m==1:
    ans=0
else:


    x.sort()

    diff=[0]*(m-1)

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

    diff.sort()

    ans=0
    if n<=m:
        for i in range(m-n):
            ans+=diff[i]
    else:
        for i in range(diff.size()):
            ans+=diff[i]

print(ans)

Submission status: Runtime Error

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

if m==1:
    print(0)
    sys.exit()

x.sort()

diff=[0]*(m-1)

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

diff.sort()

ans=0
if n<=m:
    for i in range(m-n):
        ans+=diff[i]
else:
    for i in range(diff.size()):
        ans+=diff[i]

print(ans)

Submission status: Runtime Error

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

diff = sorted([i - j for i, j in zip(x[1:], x[:-1])], reverse=True)
diff0 = diff[:N-1]
diff1 = set(diff[:N-1])


if N >= M:
    print(0)
elif N == 1:
    print(max(x)-min(x))
else:
    j = 0
    ans = 0
    for i in range(M-1):
        a = x[i+1] - x[i]
        if a in diff1 and len(diff0) != 0:
            if i - j >= 1:
                ans += x[i] - x[j]
            diff0.remove(a)
            j = i+1
            if len(diff0) == 0:
                ans += x[-1] - x[i+1]
                break
    print(ans)

Submission status: Runtime Error

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

diff = sorted([i - j for i, j in zip(x[1:], x[:-1])], reverse=True)
diff0 = diff[:N-1]
diff1 = set(diff[:N-1])


if N == 1:
    print(max(x)-min(x))
else:
    j = 0
    ans = 0
    for i in range(M-1):
        a = x[i+1] - x[i]
        if a in diff1 and len(diff0) != 0:
            if i - j >= 1:
                ans += x[i] - x[j]
            diff0.remove(a)
            j = i+1
            if len(diff0) == 0:
                ans += x[-1] - x[i+1]
                break
    print(ans)

Submission status: Runtime Error

Solution code:
import heapq
n,m=map(int,input().split())
x=sorted(list(map(int,input().split())))
diff=[]
heapq.heapify(diff)
if n>=m:
    print(0)
else:
    for i in range(m-1):
        heapq.heappush(diff,x[i]-x[i+1]-1)
    temp=0
    for _ in range(n-1):
        temp-=heapq.heappop(diff)
        #print(-heapq.heappop(diff))
print(x[m-1]-x[0]+1-temp)

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n, k = map(int, input().split())
pp = tuple(sorted(map(int, input().split())))
intv = []
for i in range(1, len(pp)):
    intv.append(pp[i] - pp[i - 1])
intv = sorted(intv)

ans = pp[-1] - pp[0]
for i in range(n - 1):
    ans -= intv[-i - 1]
print(ans)

Submission status: Runtime Error

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

arr=np.array(sorted(x))
dif=np.diff(arr)

lis=dif.tolist()
lis=sorted(lis,reverse=True)

if m>1:
    for i in range(n-1):
        lis.pop(0)

print(sum(lis))

Submission status: Runtime Error

Solution code:
import fractions
import sys
from functools import reduce
import math

input = sys.stdin.readline

def main():
    n, m = input_list()
    x = list(sorted(input_list()))
    diffs = []
    for i in range(1, m):
        a = x[i] - x[i-1]
        diffs.append((i, a))
    dd = list(sorted(diffs, key=lambda v: v[1], reverse=True))
    args = [d[0] for d in dd[:n-1]]
    r = divide_list(x, args)
    ans = 0
    for xx in r:
        ans += max(xx) - min(xx)
    print(ans)


def divide_list(l, args):
    result = []
    pre = 0
    for i, a in enumerate(args):
        if i != 0:
            pre = args[i-1]
        result.append(l[pre:a])
        if i == len(args) - 1:
            result.append(l[a:])
    return result

def divide_two(n):
    c = 0
    while True:
        if c >= 2:
            break
        if n % 2 != 0:
            break
        n //= 2
        c += 1
    return c

def get_camulative(l):
    import itertools
    # 累積和
    return [0] + list(itertools.accumulate(l))

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))


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


def input_list_str():
    return list(map(str, input().split()))


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


def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)


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


def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
# 隣との距離が大きいところで担当区間を区切るのがお得。
# 各担当区間では行ったり来たりせずに端から端まで動くのがお得。

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

if n >= m:
    print(0)
else:
    intervals = sorted([(xs[i + 1] - xs[i], i) for i in range(m - 1)], reverse=True)

    divides = sorted([ind for _, ind in intervals[:n - 1]])

    total = 0
    for i in range(len(divides) + 1):
        if i == 0:
            interval = xs[divides[i]] - xs[0]
        elif i < len(divides):
            interval = xs[divides[i]] - xs[divides[i - 1] + 1]
        else:
            interval = xs[-1] - xs[divides[i - 1] + 1]

        total += interval

    print(total)

Submission status: Runtime Error

Solution code:
# 隣との距離が大きいところで担当区間を区切るのがお得。
# 各担当区間では行ったり来たりせずに端から端まで動くのがお得。

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

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

divides = sorted([ind for _, ind in intervals[:n - 1]])

if n >= m:
    print(0)
else:
    total = 0
    for i in range(len(divides) + 1):
        if i == 0:
            interval = xs[divides[i]] - xs[0]
        elif i < len(divides):
            interval = xs[divides[i]] - xs[divides[i - 1] + 1]
        else:
            interval = xs[-1] - xs[divides[i - 1] + 1]

        total += interval

    print(total)

Submission status: Runtime Error

Solution code:
# 隣との距離が大きいところで担当区間を区切るのがお得。
# 各担当区間では行ったり来たりせずに端から端まで動くのがお得。

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

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

divides = sorted([ind for _, ind in intervals[:n - 1]])

if n >= m:
    print(0)
else:
    total = 0
    for i in range(len(divides) + 1):
        if i == 0:
            interval = xs[divides[i]] - xs[0]
        elif i < len(divides):
            interval = xs[divides[i]] - xs[divides[i - 1] + 1]
        else:
            interval = xs[-1] - xs[divides[i - 1] + 1]

        total += interval

print(total)

Submission status: Runtime Error

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

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

x.sort()

y=[0]*(m-1)
for i in range(m-1):
    y[i]=x[i+1]-x[i]
if n==1:
    print(sum(y))
    exit()
y.sort(reverse=True)
for i in range(n-1):
    del y[i]
print(sum(y))

Submission status: Runtime Error

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

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

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

y.sort(reverse=True)
for i in range(n-1):
    del y[i]
print(sum(y))

Submission status: Runtime Error

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

x.sort()

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

y.sort(reverse=True)
for i in range(n-1):
    del y[i]
print(sum(y))

Submission status: Runtime Error

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

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

print(sum(D[M+1:]))

Submission status: Runtime Error

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

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
if m <= n:
  print(0)
  exit()

if n%2 == 0:
  cutl = n//2 - 1
  cutr = len(x)+1-(n//2)
else:
  cutl = (n//2)
  cutr = len(x)-1+(n//2)

lis = x[cutl:cutr]
l = []

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

print(lis[-1] - lis[0] -max(l))

Submission status: Runtime Error

Solution code:
n,m = map(int,input().split())
x = list(map(int,input().split()))
x.sort()
if m == 1:
  print(0)
  exit()

if n%2 == 0:
  cutl = n//2 - 1
  cutr = len(x)+1-(n//2)
else:
  cutl = (n//2)
  cutr = len(x)-1+(n//2)

lis = x[cutl:cutr]
l = []

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

print(lis[-1] - lis[0] -max(l))

Submission status: Runtime Error

Solution code:
N, M = list(map(int,input().split()))
X = list(map(int,input().split()))
X = sorted(X)
diff = [None for _ in range(M-1)]
for i in range(M-1):
  diff[i] = X[i+1] - X[i]
diff = sorted(diff)
ans = 0
if N >= M:
  ans = 0
else:
  for i in range(N+1):
    ans += diff[i]
print(ans)

Submission status: Runtime Error

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

X = sorted(X)
if N == 1:
    print(abs(X[M-1] -X[0]))
else:
    A=[]
    for i in range(M-1):
        A.append(abs(X[i]-X[i+1]))
print(sum(sorted(A)[:M-N]))

Submission status: Runtime Error

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

Submission status: Runtime Error

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