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

Submission status: Time Limit Exceeded

Solution code:
def game(n, m, x_list):
  if n >= m:
    return 0
  
  x_list.sort()
  interval = []
  for i in range(m - 1):
    interval.append(x_list[i + 1] - x_list[i])
    interval.sort(reverse = True)
    if len(interval) > n - 1:
      del(interval[n - 1])
  
  return abs(x_list[m - 1] - x_list[0]) - sum(interval)

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

print(game(n, m, x))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
N, M= map(int, input().split())
zahyo = []
for i in map(int,input().split()):
    zahyo += [i]
sum=0
for i in range(M-1):
    for j in range(M):
        if i < j:
            if zahyo[i] > zahyo[j]:
                a = zahyo[i]
                zahyo[i] = zahyo[j]
                zahyo[j] = a
gap = []
for i in range(M-1):
    gap += [zahyo[i+1]-zahyo[i]] 
for i in range(M-2):
    for j in range(M-1):
        if i < j:
            if gap[i] < gap[j]:
                a = gap[i]
                gap[i] = gap[j]
                gap[j] = a
if N >= M:
    print(0)
elif N == 1:
    print(zahyo[M-1] - zahyo[0])
else:
    for i in gap[N-1:]:
        sum += i
    print(sum)

Submission status: Time Limit Exceeded

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

if M < N:
  print(0)
else:
  xs = sorted(XS)
  ds = list(map(lambda a,b: b-a, xs, xs[1:]))
  for _ in range(N-1):
    ds.remove(max(ds))

  print(sum(ds))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
a = list(map(int,input().split()))
b = list(map(int,input().split()))
b.sort()

c = []
if len(b) != 1:
  for i in range(len(b) - 1):
    c.append(b[i+1] - b[i])

if len(b) == 1:
  print(0)
  
    
else:  
  for j in range(min(a[0] - 1,a[1])):
    for k in range(len(c)):
      if c[k] == max(c):
        c[k] = 0
        break
  print(sum(c))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int, input().split( ))
datas = list(map(int, input().split( )))
datas.sort()
Ms = M - 1

dest = list()
K = 0
i = 0
for i in range(Ms):
  K = datas[i+1] - datas[i]
  dest.append(K)
  dest.sort()

L = 0
MN = M - N
for j in range(MN):
  L = L + dest[j]

print(L)

Submission status: Time Limit Exceeded

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

if n < m:
  l.sort()
  for i in range(m-1):
    sa.append(l[i+1]-l[i])

  for i in range(n-1):
    sa.remove(max(sa))

  print(sum(sa))
else:
  print(0)

Submission status: Time Limit Exceeded

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

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

    x = sorted(list(map(int, input().split())))
    if n==1:
        print(x[-1]-x[0])
        sys.exit()

    dp = [[x[-1]-x[0]]*(n) for _ in range(m)]
    for i in range(1,m):
        for j in range(n-2, -1, -1):
            dp[i][j] = min(dp[i-1][j], dp[i-1][j+1]-(x[i]-x[i-1]))
    print(dp[m-1][0])

if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

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

if n >= m:
    print(0)
else:
    sumdis = sum(map(lambda a: a[1], x))
    h = 0
    skipdis = 0
    while h < n - 1:
        maxdis = max(x, key=lambda a: a[1])
        skipdis += maxdis[1]
        x.remove(maxdis)
        h += 1
    print(sumdis - skipdis)

Submission status: Time Limit Exceeded

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

if n >= m:
    print(0)
    exit()
else:
    difference = []
    x.sort()
 
    for i in range(m-1):
        difference.append(x[i+1]-x[i])
 
    for i in range(n-1):
        difference.remove(max(difference))
 
    print(sum(difference))

Submission status: Time Limit Exceeded

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

x_sort = sorted(x_arr)
x_sub = []

if n >= m:
    print(0)
else:
    x_sub = [x_sort[i+1]-x_sort[i] for i in range(m-1) ]
    
    for i in range(n-1):
        x_sub.remove(max(x_sub))
    
    print(sum(x_sub))

Submission status: Time Limit Exceeded

Solution code:
import sys

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

    if N >= M:
        print('0')
        return

    def _compute_delta(i, j):
        s = 0
        for k in range(i, j - 1):
            s += X[k + 1] - X[k]
        return s

    def _compute(pos):
        debug_pos = pos
        s, i, j = 0, 0, 1
        debug = []
        while pos > 0:
            if (pos & 1) == 0:
                j += 1
                pos = pos >> 1
                continue
            s += _compute_delta(i, j)
            # debug.append((_compute_delta(i, j), (i, j)))
            i = j
            j += 1
            pos = pos >> 1
        s += _compute_delta(i, len(X))
        # debug.append((_compute_delta(i, len(X)), (i, len(X))))
        # print(bin(debug_pos), s, debug)
        return s

    # print()
    # print(X)

    pos = (1 << (N - 1)) - 1
    max_pos = 1 << (M - 1)
    min_s = _compute(pos)

    def _next(p):
        while True:
            p += 1
            if p >= max_pos:
                return None
            if bin(p).count('1') == N - 1:
                return p

    while True:
        pos = _next(pos)
        if pos is None:
            break
        min_s = min(min_s, _compute(pos))
    print(min_s)

main()

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
x=input().split()
for i in range(m):
    a=int(x[i])
    x[i]=a
if n==1:
    print(max(x)-min(x))
elif m==1 or n>=m:
    print(0)
else:
    goukei=0
    l=[0]
    i=0
    x.sort()
    a=0
    b=0
    if m>1:
        while i<m-1:
            a=x[i]
            b=x[i+1]
            goukei+=b-a
            l.append(b-a)
            i+=1
    i=0
    l.sort()
    while i<n-1:
        a=max(l)
        goukei-=a
        l.remove(a)
        i+=1
        if l==[]:
            break
    print(goukei)

Submission status: Time Limit Exceeded

Solution code:
#coding: utf-8
N, M = map(int, input().split())
points = list(map(int, input().split()))
points = sorted(points)
koma = [points[i+1] - points[i] for i in range(M-1)]
sum_ = 0
for i in range(M-N):
  sum_ += min(koma)
  koma.remove(min(koma))
print(sum_)

Submission status: Time Limit Exceeded

Solution code:
def psolve(k, Xs, N):
    arr = [[]]
    i = Xs[0]
    for x in Xs:
        if x <= i + k:
            arr[-1].append(x)
        else:
            arr.append([])
            arr[-1].append(x)
            i = x
            if len(arr) > N:
                break

    if len(arr) <= N:
        ans = sum([max(a) - min(a) for a in arr])
        return ans
    else:
        return 10 ** 9


def solve(N, M, Xs):
    Xs = sorted(Xs)
    ans = 10 ** 9
    for k in range(0, (Xs[-1] - Xs[0]) + 1):
        nans = psolve(k, Xs, N)
        ans = min(ans, nans)
    return ans


if __name__ == "__main__":
    N, M = tuple(map(int, input().split(" ")))
    Xs = list(map(int, input().split(" ")))
    print(solve(N, M, Xs))

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

def main(inp):
    N,M=map(int,next(inp).split())
    X=np.array(list(map(int,next(inp).split())))
    X=np.sort(X)
    
    if(N>M): return 0
    if(N==1):
        ans=X[len(X)-1]-X[0]
        return ans
    
#     print(N,M,X)
    
    delta=np.empty([M-1],dtype=int)
    
    for i in range(M-1):
        delta[i]=X[i+1]-X[i]
    
#     print(X)
#     print(delta)
    
    
    #delta=np.split(delta,[1,2])
    #print(delta)
    
    splpoint=np.argpartition(np.array(delta),-N+1)[-N+1:]
    splpoint=np.sort(splpoint)
    for i in range(len(splpoint)):
        splpoint[i]+=1
    
#     delta=np.delete(delta,splpoint)
#     print(delta)    
#     print(splpoint)
    
    spl=np.split(X,splpoint)
#     print(spl)
    
    ans=0
    for i in range(len(spl)):
        ans+=spl[i][len(spl[i])-1]-spl[i][0]
        
    return ans
  
print(main(sys.stdin))

Submission status: Time Limit Exceeded

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

import itertools


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

    if N >= M:
        print(0)
        return

    result = None
    for p in itertools.product(range(M + 1), repeat=N):
        if sum(p) != M:
            continue

        start, count = 0, 0
        for c in p:
            if c < 1:
                continue
            count += Xs[start + c - 1] - Xs[start]
            start += c
            if start >= M:
                break
        if not result or count < result:
            result = count

    print(result)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def _solve(current, n, idx, x):
    if n >= len(x) - idx:
        return 0

    if n == 0:
        return x[-1] - current


    if current is None:
        return solve(x[idx], n - 1, idx + 1, x)

    a = x[idx] - current + solve(x[idx], n, idx + 1, x)
    b = solve(x[idx], n - 1, idx + 1, x)
    return min(a, b)

def solve(n, m, x):
    if n >= m:
        return 0

    dp = [[0 for _ in range(n + 1)] for _ in range(m)]
    dp[m-1][0] = x[-1] - x[-2]
    for i in range(1, n + 1):
        dp[m-1][i] = 0

    for idx in reversed(range(m - 1)):
        for i in range(n + 1):
            if i >= m - idx + 1:
                dp[idx][i] = 0
            elif i == 0:
                dp[idx][i] = x[-1] - x[idx-1]
            elif idx == 0:
                dp[idx][i] = dp[idx+1][i-1]
            else:
                a = x[idx] - x[idx - 1] + dp[idx+1][i]
                b = dp[idx+1][i-1]
                dp[idx][i] = min(a, b)

    return dp[0][n]

def main():
    n, m = map(int, input().split())
    x = [int(s) for s in input().split()]
    x.sort()

    print(solve(n, m, x))

main()

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
if n==1:
    print(max(x)-min(x))
elif m==1 or n>=m:
    print(0)
else:
    goukei=0
    l=[0]
    i=0
    x.sort()
    a=0
    b=0
    if m>1:
        while i<m-1:
            a=x[i]
            b=x[i+1]
            goukei+=b-a
            l.append(b-a)
            i+=1
    i=0
    l.sort()
    while i<n-1:
        a=max(l)
        goukei-=a
        l.remove(a)
        i+=1
        if l==[]:
            break
    print(goukei)

Submission status: Time Limit Exceeded

Solution code:
def seek(old_list, current_score):
    new_list = []
    subs = [min(old_list[i+1]) - max(old_list[i]) for i in range(len(old_list)-1)]
    min_index = subs.index(min(subs))
    current_score += min(subs)
    old_list[min_index] = old_list[min_index] | old_list[min_index+1]
    old_list.remove(old_list[min_index+1])
    if(len(old_list) == N):
        return [], current_score
    else:
        return seek(old_list, current_score)

N, M = map(int, input().strip().split())
komas = list(map(int, input().strip().split()))
komas.sort()
komas_set = [set([k]) for k in komas]

if(N >= M):
    print(0)
else:
    print(seek(komas_set, 0)[1])

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int, input().strip().split())
list_x_str = input().strip().split()
list_x = [int(s) for s in list_x_str]
list_x.sort()

diff_list = []
if m <= n:
    print('0')
else:

    for i in range(len(list_x)):
        if len(list_x) == i + 1:
            break

        diff_list.append(list_x[i + 1] - list_x[i])

    for _ in range(n - 1):
        diff_list.remove(max(diff_list))

    print(sum(diff_list))

Submission status: Time Limit Exceeded

Solution code:
#coding: utf-8
N, M = map(int, input().split())
points = list(map(int, input().split()))
points.sort()
koma = [points[i+1] - points[i] for i in range(M-1)]
sum_ = 0
for i in range(M-N):
  sum_ += min(koma)
  koma.remove(min(koma))
print(sum_)

Submission status: Time Limit Exceeded

Solution code:
def seek(old_list, current_score):
    new_list = []
    subs = [min(old_list[i+1]) - max(old_list[i]) for i in range(len(old_list)-1)]
    min_index = subs.index(min(subs))
    current_score += min(subs)
    for i in range(len(old_list)):
        if(i == min_index):
            continue
        elif(i == min_index + 1):
            new_list.append(old_list[i] | old_list[i-1])
        else:
            new_list.append(old_list[i])
    if(len(new_list) == N):
        return [], current_score
    else:
        return seek(new_list, current_score)

N, M = map(int, input().strip().split())
komas = list(map(int, input().strip().split()))
komas.sort()
komas_set = [set([k]) for k in komas]

if(N >= M):
    print(0)
else:
    print(seek(komas_set, 0)[1])

Submission status: Time Limit Exceeded

Solution code:
import sys

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

# 座標数よりコマ数が多ければ初期位置で条件を満たす
if N >= M:
    print(0)
    sys.exit()

# ソートする
X.sort()

# 隣り合う数の差を計算する
diff = list()
for m in range(M-1):
    diff.append(X[m+1] - X[m])

for n in range(N-1):
    max_index = diff.index(max(diff))
    diff.pop(max_index)

print(sum(diff))

Submission status: Time Limit Exceeded

Solution code:
import itertools

N, M= (int(i) for i in input().split())
X = list(int(i) for i in input().split())
X.sort()

if(N >= M):
    print(0)
else:
    combination = list(itertools.combinations(range(M),N-1))
    min = 2 * 100000
    for tmp_taple in combination:
        tmp_sum = 0
        from_index = 0
        for to_index in tmp_taple:
            tmp_sum += X[to_index] - X[from_index]
            from_index = to_index + 1
        if(from_index < M-1):
            tmp_sum += X[M-1] - X[from_index]
        if(min > tmp_sum):
            min = tmp_sum
    print(min)

Submission status: Time Limit Exceeded

Solution code:
N,M = map(int,input().split())
Xs = list(map(int,input().split()))
Xs.sort()
Xdivs = []
for i in range(M-1):
    Xdivs.append(Xs[i+1]-Xs[i])
for _ in range(N-1):
    for i,x in enumerate(Xdivs):
        if Xdivs[i] == max(Xdivs):
            Xdivs[i] = 0
            break
print(sum(Xdivs))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

def main(N, X):
    dp = [0] * N
    for i in range(1, len(X)):
        dX = X[i] - X[i-1]
        for j in range(N-1, 0, -1):
            dp[j] = min(dp[j-1], dp[j] + dX)
        dp[0] = dp[0] + dX
    print(dp[-1])

def parse(inp):
    N, M = map(int, next(inp).split())
    X = list(sorted(map(int, next(inp).split())))
    return N, X

main(*parse(stdin))

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
if n==1:
    print(max(x)-min(x))
elif m==1 or n>=m:
    print(0)
else:
    goukei=0
    l=[0]
    i=0
    x.sort()
    a=0
    b=0
    while i<m-1:
        a=x[i]
        b=x[i+1]
        goukei+=b-a
        l.append(b-a)
        i+=1
    for v in range(n-1):
        goukei-=max(l)
        l.remove(max(l))
    print(goukei)

Submission status: Time Limit Exceeded

Solution code:
import itertools

N, M= (int(i) for i in input().split())
X = list(int(i) for i in input().split())
X.sort()

if(N >= M):
    print(0)
else:
    X_index = range(M) # 0~N-1の連続リスト
    combination = list(itertools.combinations(X_index,N-1))
    min = 2 * 100000
    for tmp_taple in combination:
        tmp_sum = 0
        from_index = 0
        for to_index in tmp_taple:
            tmp_sum += X[to_index] - X[from_index]
            from_index = to_index + 1
        if(from_index < M-1):
            tmp_sum += X[M-1] - X[from_index]
        if(min > tmp_sum):
            min = tmp_sum
    print(min)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

if n >= m:
    print(0)
else:
    npx = np.array(x)
    li = list(np.diff(npx, n = 1))

    for i in range(n-1):
        li.remove(max(li))

    print(sum(li))

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
if n==1:
    print(max(x)-min(x))
elif m==1 or n>=m:
    print(0)
else:
    goukei=0
    l=[0]
    i=0
    while i<m-1:
        goukei+=x[i+1]-x[i]
        l.append(x[i+1]-x[i])
        i+=1
    i=0
    while i<n-1:
        goukei-=max(l)
        l.remove(max(l))
        i+=1
    print(goukei)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M=map(int,input().split(" "))
if M>N:
    A=list(sorted(map(int,input().split(" "))))
    L=np.array([A[s]-A[s+1] for s in range(M-1)])
    for s in range(N-1):
        L[np.argmin(L)]=0
    print(abs(sum(L)))
else:
    print(0)

Submission status: Time Limit Exceeded

Solution code:
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
c = []
ii = 0
if a[1] <= a[0]:
    print(ii)
elif a[1] == 1:
    print(ii)
else:
  if a[1] > 1:
    for i in range(0, a[1] - 1):
      d = b[i + 1] - b[i]
      c.append(d)
    
  if a[0] >= 2:
    for i in range(0, a[0] - 1):
      f = max(c)
      c.remove(f) 
  if a[1] != 1:
    print(sum(c))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M=map(int,input().split(" "))
A=list(sorted(map(int,input().split(" "))))
L=np.array([A[s]-A[s+1] for s in range(M-1)])

if M>N:
    for s in range(N-1):
        L[np.argmin(L)]=0
    print(abs(sum(L)))
else:
    print(0)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M=map(int,input().split(" "))
A=list(sorted(map(int,input().split(" "))))
L=np.array([A[s]-A[s+1] for s in range(M-1)])

if M<=N:
    print(0)
else:
    for s in range(N-1):
        L[np.argmin(L)]=0
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

Solution code:
n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
if n==1:
    print(max(x)-min(x))
elif m==1 or n>=m:
    print(0)
else:
    x.sort()
    goukei=0
    l=[0]
    for i in range(m-1):
        goukei+=x[i+1]-x[i]
        l.append(x[i+1]-x[i])
    i=0
    for i in range(n-1):
        goukei-=max(l)
        l.remove(max(l))
    print(goukei)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M=map(int,input().split(" "))
#Nはポーンの数 Mは入力の数
A=list(sorted(map(int,input().split(" "))))
L=np.array([A[s]-A[s+1] for s in range(M-1)])

if M<=N:
    print(0)
else:
    for s in range(N-1):
        L[np.argmin(L)]=0
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N,M=map(int,input().split(" "))
#Nはポーンの数 Mは入力の数
A=list(sorted(map(int,input().split(" "))))
L=np.array([A[s]-A[s+1] for s in range(M-1)])

if M<=N:
    print(0)
else:
    for s in range(N-1):
        L=np.delete(L,np.argmin(L))
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

Solution code:
import sys

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

List=[]
max_list=[]

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


for i in range(len(X_list)):
	if i==len(X_list)-1:
		break
	tmp=abs(X_list[i]-X_list[i+1])
	List.append(tmp)
	if N==1:
		pass

	elif len(max_list)<N-1:
		max_list.append(tmp) 
	elif len(max_list)==N-1:
		if min(max_list)<tmp:
			max_list.append(tmp)
			max_list.remove(min(max_list))
		else:
			pass
	else:
		pass

cnt=sum(List)-sum(max_list)

print(cnt)

Submission status: Time Limit Exceeded

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

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

if M > N:
    
    for i in range(N-1):
        difX.pop(difX.index(max(difX)))

    total = 0
    for x in difX:
        total+= x

    print(total)
else:
    print(0)

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split(" "))
#Nはポーンの数 Mは入力の数
A=sorted(map(int,input().split(" ")))
L=[list(A)[s]-list(A)[s+1] for s in range(M-1)]

if M<=N:
    print(0)
else:
    for s in range(N-1):
        L.remove(min(L))
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

Solution code:
def psolve(k, Xs, N):
    arr = [[]]
    i = Xs[0]
    for x in Xs:
        if x <= i + k:
            arr[-1].append(x)
        else:
            arr.append([])
            arr[-1].append(x)
            i = x
            if len(arr) > N:
                break

    if len(arr) <= N:
        ans = sum([max(a) - min(a) for a in arr])
        return ans
    else:
        return 10 ** 9


def solve(N, M, Xs):
    Xs = sorted(Xs)
    ans = 10 ** 9
    for k in range(0, (Xs[-1] - Xs[0]) + 1):
        ans = min(ans, psolve(k, Xs, N))
    return ans


if __name__ == "__main__":
    N, M = tuple(map(int, input().split(" ")))
    Xs = list(map(int, input().split(" ")))
    print(solve(N, M, Xs))

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split(" "))
#Nはポーンの数 Mは入力の数
A=list(sorted(map(int,input().split(" "))))
L=[A[s]-A[s+1] for s in range(M-1)]

if M<=N:
    print(0)
else:
    for s in range(N-1):
        L.remove(min(L))
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

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

row_x = input().split()
for i in range(m):
    row_x[i] = int(row_x[i])

if n >= m:
    print(0)
else:
    difference = []
    x = sorted(row_x)

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

    for i in range(n-1):
        difference.remove(max(difference))

    print(sum(difference))

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
import math
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()
def IIR(n): return [II() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
mod = 1000000007

#A
"""
t,x = LI()
print(t/x)
"""

#B
"""
n= II()
a = LI()
m = max(a)
if m >= sum(a)-m:
    print("No")
else:
    print("Yes")
"""
#C
n,m = LI()
x = LI()
x.sort()
l = [x[i+1]-x[i] for i in range(m-1)]
l.sort()
l = l[::-1]
for i in range(n-1):
    if len(l) == 0:
        print(0)
        quit()
    l.pop(0)
print(sum(l))
#D
"""
n,k = LI()
a = LI()
l = 0
b = [0 for i in range(n)]
for i in range(n):
    b[i] = list(bin(a[i]))[2:]
    l = max(l,len(b[i]))
s = [0 for i in range(l)]
for i in range(n):
    for j in range(l-len(b[i])):
        b[i].insert(0,"0")
for i in range(n):
    for j in range(l):
        s[j] += 1-int(b[i][j])
ke = 1
for i in range(l)[::-1]:
    if s[i] <= n//2:
        s[i] = [(n-s[i])*ke,0,float("inf")]
    else:
        s[i] = [(n-s[i])*ke,s[i]*ke,ke]
    ke *= 2
s.sort(key = lambda x:x[0])
d = 0
ans = 0
key = len(list(bin(k)))-2
key -= l
ke = 2**l
print(s)
for i in range(key):
    d += ke
    ans += n*ke
    ke *= 2
for i in range(l):
    r,q,p = s[i]
    if d+p <= k:
        d += p
        ans += q
    else:
        ans += r
print(ans)
"""
#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n_dices, n_points = map(int, input().split())
points = sorted(list(map(int, input().split())))
if n_dices >= n_points:
    print(0)
    sys.exit()
interval_list = [points[i + 1] - points[i] for i in range(n_points - 1)]
for i in range(n_dices - 1):
    interval_list.pop(interval_list.index(max(interval_list)))
print(sum(interval_list))

Submission status: Time Limit Exceeded

Solution code:
### C

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

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

#print("X = " + str(X))

D = []

R = 0

if M-1 > 0 :
	for i in range(M-1):
		D.append(int(X[i+1]) - int(X[i]))


#print("D = " + str(D))

for i in range(N-1):
	if D !=[]:
		MAXD = max(D)
		D.remove(MAXD)
#		print(str(D) + "minus " + str(i+1) + "roots.")

if D != []:
	for d in D:
		R += d


print(R)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

xs=sorted(x)
# xs

# def sabun(x,i):
#     return x[i+1]-x[i]

def sabun(x):
    a=np.array(x)
    return list(a[1:]-a[:-1])

# sabunx=[sabun(xs,i) for i in range(m-1)]

sabunx=sabun(xs)
# sabunx

for _ in range(n-1):
    sabunx.remove(sabunx[sabunx.index(sorted(sabunx,reverse=True)[0])])
#     print(sabunx)
    
print(sum(sabunx))

Submission status: Time Limit Exceeded

Solution code:
#coding: utf-8
N, M = map(int, input().split())
points = list(map(int, input().split()))
points.sort()
koma = [points[i+1] - points[i] for i in range(M-1)]
sum_ = 0
for i in range(M-N):
  sum_ += min(koma)
  koma.remove(min(koma))
print(sum_)

Submission status: Time Limit Exceeded

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


Xs.sort()
costs=[abs(Xs[i]-Xs[i+1]) for i in range(M-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:
from sys import stdin
import numpy as np

def main(N, X):
    dp = np.zeros(N, dtype=np.int64)
    for i in range(1, len(X)):
        dX = X[i] - X[i-1]
        for j in range(N-1, 0, -1):
            dp[j] = min(dp[j-1], dp[j] + dX)
        dp[0] = dp[0] + dX
    print(dp[-1])

def parse(inp):
    N, M = map(int, next(inp).split())
    X = list(sorted(map(int, next(inp).split())))
    return N, X

main(*parse(stdin))

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split(" "))
#Nはポーンの数 Mは入力の数
A=list(map(int,input().split(" ")))
A=sorted(A)
L=[A[s]-A[s+1] for s in range(M-1)]

if M<=N:
    print(0)
else:
    for s in range(N-1):
        L.remove(min(L))
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

Solution code:
### C

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

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

X = list(map(int , sorted(X)))

#print("X = " + str(X))

D = []

R = 0

if M-1 > 0 :
	for i in range(M-1):
		D.append(int(X[i+1]) - int(X[i]))


#print("D = " + str(D))

for i in range(N-1):
	if D !=[]:
		MAXD = max(D)
		D.remove(MAXD)
#		print(str(D) + "minus " + str(i+1) + "roots.")

if D != []:
	for d in D:
		R += d


print(R)

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split(" "))
#Nはポーンの数 Mは入力の数
A=list(map(int,input().split(" ")))
A=sorted(A)
L=[]
for s in range(M-1):
    L.append(A[s]-A[s+1])
if M<=N:
    print(0)
else:
    for s in range(N-1):
        L.remove(min(L))
    print(abs(sum(L)))

Submission status: Time Limit Exceeded

Solution code:
import sys

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

Dict={}

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

for i in range(len(X_list)):
	if i==len(X_list)-1:
		break
	Dict[i]=abs(X_list[i]-X_list[i+1])

for n in range(N-1):
	tmp_max=max(Dict, key=Dict.get)
	del Dict[tmp_max]

cnt=0
for v in Dict.values():
	cnt+=v

print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int,input().split())
X = [int(x) for x in input().split()]
X.sort(reverse=True)
valX = [X[x] - X[x + 1] for x in range(M - 1)]

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

if N == 1:
    print(max(X) - min(X))
    exit()

for i in range(1,N):
    valX[valX.index(max(valX))] = 0

print(sum(valX))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n,m = map(int,input().split())
x = np.array(list(map(int, input().split())))
if n>= m:
    print(0)
    exit()
x.sort()
xd = np.diff(x)
xd2=xd.tolist()
for i in range(n-1):
    xd2.remove(max(xd2))
print(sum(xd2))

Submission status: Time Limit Exceeded

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

xs=sorted(x)
# xs

def sabun(x,i):
    return x[i+1]-x[i]

sabunx=[sabun(xs,i) for i in range(m-1)]
# sabunx

for _ in range(n-1):
    sabunx.remove(sabunx[sabunx.index(sorted(sabunx,reverse=True)[0])])
#     print(sabunx)
    
print(sum(sabunx))

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:
    #コマの数が少ない時は全体から引く
    if (m-1)/2 >= n-1:
        for v in itertools.combinations(kaisa_list,n-1):
            #print(v)
            #print(mini)
            #print(sum(kaisa_list)-sum(v))
            mini = min(mini,sum(kaisa_list)-sum(v))
        print(mini)
    else:
        #コマの数が多い時は要素を足し合わせる
        for v in itertools.combinations(kaisa_list,m-n):
            #print(v)
            mini = min(mini,sum(v))
        print(mini)

"""
階差のリストのうちn-1個要素を減らして合計値の最小値で求める

"""

Submission status: Time Limit Exceeded

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