Problem:


Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

Print the minimum possible value of h_{max} - h_{min}.

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).



Sample input:
5 3
10
15
11
14
12


Sample output:
2

Submission status: Accepted

Solution code:
N,K=map(int, input().split(' '))
wood = []
difference = []
for i in range (N):
  wood.append(int(input()))
wood.sort()
  
for i in range(N-K+1):
  difference.append(wood[K + i - 1] - wood[i])
print(min(difference))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
h = [int(input()) for i in range(N)]
h.sort()
print(min(h[i+K-1] - h[i] for i in range(N-K+1)))

Submission status: Accepted

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

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n, k = mi()
    h = [ii() for _ in range(n)]
    h.sort()
    ans = inf
    for i in range(n - k + 1):
        j = i + (k - 1)
        ans = min(ans, h[j] - h[i])
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = [int(input()) for _ in range(n)]

sorted_trees = sorted(h, reverse=True)

minimum = float('inf')
for i in range(n-(k-1)):
    diff = sorted_trees[i] - sorted_trees[i+(k-1)]
    if diff < minimum:
        minimum = diff
print(minimum)

Submission status: Accepted

Solution code:
N,K = map(int,input().split())
ls = []
for i in range(N):
  ls.append(int(input()))
ls.sort()
ls.reverse()
minimum = 10**10
for i in range(N-K+1):
  if ls[i]-ls[i+K-1] < minimum:
    minimum = ls[i]-ls[i+K-1]
print(minimum)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline

    N, K = map(int, input().split())
    h = [int(input()) for _ in range(N)]
    h.sort()

    ans = 1 << 30
    left = 0
    while left + K - 1 < N:
        right = left + K - 1
        d = h[right] - h[left]
        if ans > d:
            ans = d
        left += 1
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from heapq import heapify, heappop, heappush
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, K = MAP()
H = [INT() for i in range(N)]
H.sort()
ans = INF
for i in range(N-K+1):
    mi = H[i]
    ma = H[i+K-1]
    tmp = ma - mi
    ans = min(tmp, ans)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = []
for i in range(n):
    h.append(int(input()))

h.sort(reverse=True)
ans = []
for i in range(n):
    if i+k-1 >= n:
        break
    ans.append(abs(h[i] - h[i+k-1]))
print(min(ans))

Submission status: Accepted

Solution code:
import sys
import numpy as np
input = sys.stdin.readline


def readstr():
    return input().strip()


def readint():
    return int(input())


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


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


def main():
    N, K = readnums()
    h = np.sort(np.array([readint() for _ in range(N)]))
    ans = 0
    for i in range(N - K + 1):
        if not i:
            ans = h[i + K - 1] - h[i]
        else:
            ans = min(ans, h[i + K - 1] - h[i])

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
li = []
lia = [0]*(n-k+1)
for i in range(n):
    li.append(int(input()))
li.sort()
for i in range(n-k+1):
    lia[i] += li[i+k-1] - li[i]
print(min(lia))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
h = [int(input()) for _ in range(n)]
h = sorted(h)

res = 10 ** 100
for i in range(n):
    j = i + k - 1
    if j >= n:
        break
    res = min(res, h[j] - h[i])
print(res)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = list(int(input()) for _ in range(n))

h.sort()

mn = 10 ** 9
for i in range(n-k+1):
    d = h[i+k-1] - h[i]
    mn = min(mn, d)

print(mn)

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
h = [int(input()) for _ in range(N)]
h = sorted(h)
ans = float('inf')
for i in range(N-K+1):
    ans = min(h[i+K-1] - h[i], ans)
print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=[int(input()) for _ in range(n)]
h.sort()
res=[]
for i in range(n-k+1):
    s=h[i+k-1]-h[i]
    res.append(s)
print(min(res))

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=[int(input()) for i in range(n)]
h.sort()
hantei=10**9+1
for i in range(len(h)-k+1):
  if (h[i+k-1]-h[i])<hantei:
    hantei=h[i+k-1]-h[i]
print(hantei)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
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,k = inpl()
a = [inp() for _ in range(n)]
a.sort()
res = INF
for i in range(n-k+1):
    res = min(res, a[i+k-1] - a[i])
print(res)

Submission status: Accepted

Solution code:
# coding: utf-8
# hello worldと表示する
#dpでできないかな？
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7
n,k=MI()
lis=sorted([I() for i in range(n)])
u=[]
for i in range(n-k+1):
    u.append(lis[i+k-1]-lis[i])
print(min(u))

Submission status: Accepted

Solution code:
def ii():return int(input())
def iim():return map(int,input().split())
def iil():return list(map(int,input().split()))
def ism():return map(str,input().split())
def isl():return list(map(str,input().split()))
n,k = iim()
h = []
for _ in range(n):
    h.append(ii())
h.sort()

ans = float('INF')
for i in range(n-k+1):
#    print(i,i+k-1,h[i],h[i+k-1])
    ans = min(ans,h[i+k-1]-h[i])
print(ans)

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
L = [int(input()) for i in range(N)]

L.sort()
ans = 10**12
for i in range(N-K+1):
    A = L[i]
    B = L[i+K-1]
    ans = min(ans,B-A)
print(ans)

Submission status: Accepted

Solution code:
def resolve():
  n, k = map(int, input().split())
  h = []
  for i in range(n):
    h.append(int(input()))
  h.sort()
  ans = 1e9+5
  for i in range(n-k+1):
    ans = min(ans, h[i+k-1] - h[i])
  print(ans)
  return

if __name__ == "__main__":
  resolve()

Submission status: Accepted

Solution code:
def resolve():
    n, k = map(int, input().split())
    h = []
    for i in range(n):
        h.append(int(input()))
    h = sorted(h)
    ans = 10**9+2
    for i in range(n-k+1):
        test = h[i+k-1]-h[i]
        ans = min(test, ans)
    print(ans)
resolve()

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
h = [int(input()) for _ in range(n)]
h.sort()
ans = float("INF")
for i in range(n-k+1):
  if ans > h[i+k-1]-h[i]: ans = h[i+k-1]-h[i]
print(ans)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n, k = map(int, input().split())
    H = sorted(list(int(input()) for _ in range(n)))

    res = f_inf
    for i in range(n - k + 1):
        diff = H[i + k - 1] - H[i]
        res = min(res, diff)

    print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = [int(input()) for i in range(n)]
h.sort()
l = []
for i in range(n - k + 1):
    l.append(h[i + k - 1] - h[i])
print(min(l))

Submission status: Accepted

Solution code:
from sys import stdin
def main():
    #入力
    readline=stdin.readline
    n,k=map(int,readline().split())
    h=[0]*n
    for i in range(n):
        h[i]=int(readline())
    h.sort()

    ans=float("inf")
    for i in range(k-1,n):
        s=h[i]-h[i-k+1]
        ans=min(s,ans)

    print(ans)
    
if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n,k = map(int,input().split())
H = [int(input()) for i in range(n)]
H.sort()
for i in range(n-k+1):
  mans = min(mans,H[i+k-1]-H[i])
print(mans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=sorted([int(input()) for i in range(n)])
a=[]
for i in range(n-k+1):
    a.append(h[i+k-1]-h[i])
print(min(a))

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

n, k = map(int, readline().split())
h = [int(readline()) for _ in range(n)]
h.sort()
ans = float('inf')
for bf, af in zip(h, h[k - 1:]):
    ans = min(ans, af - bf)
print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
a = [0] * N
for i in range(N): a[i] = int(input())
a.sort()
res = float("inf")
for i in range(N - K + 1):
  res = min(res, a[i + K - 1] - a[i])
print(res)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=[int(input()) for _ in range(n)]
h=sorted(h)
l=[]
for i in range(n-k+1):
  l.append(h[i+k-1]-h[i])
print(min(l))

Submission status: Accepted

Solution code:
n , k = map(int,input().split())
h = [int(input()) for i in range(n)]
h.sort()
ans = 10**9
for i in range(n-k+1):
    ans = min(ans,h[i+k-1]-h[i])
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = []

for i in range(n):
  h.append(int(input()))
h.sort()

ans = []
for i in range(0,len(h)-k+1):
  ans.append(h[i+k-1] - h[i])

print(min(ans))

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
h=[]
for _ in range(n):
    h.append(int(input()))

ans=1000000000
h.sort()
for i in range(n-k+1):
    tmp=h[i+k-1]-h[i]
    ans=min(ans,tmp)
print(ans)

Submission status: Accepted

Solution code:
def main():
    N, K = list(map(int, input().split(' ')))
    H = [int(input()) for _ in range(N)]
    H.sort()
    min_diff = H[-1] - H[0]
    for i in range(N - K + 1):
        min_diff = min([min_diff, H[i + K - 1] - H[i]])
    print(min_diff)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7
#s=input().rstrip()

n,k=MI()
u=[]
lis=sorted([I() for i in range(n)])
for i in range(n-k+1):
    u.append(lis[i+k-1]-lis[i])
print(min(u))

Submission status: Accepted

Solution code:
n, k = [int(i) for i in input().split()]
h = sorted([int(input()) for i in range(n)])
mn = 10 ** 9
for i in range(n-k+1):
    mn = min(mn, h[i+k-1] - h[i])
print(mn)

Submission status: Accepted

Solution code:
from collections import deque

n,k = map(int,input().split())

h = []
for i in range(n):
	h.append(int(input()))

h.sort()
h = deque(h)
d = []
d = deque(d)

for _ in range(k):
	d.append(h.popleft())

ans = d[-1] - d[0]
for _ in range(n-k):
	d.popleft()
	d.append(h.popleft())
	num = d[-1] - d[0]
	if ans > num:
		ans = num
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
h = [0]*n
for i in range(n):
  h[i] = int(input())
h.sort()
hdf = 10**9
for i in range(n-k+1):
  hdf = min(hdf,h[k+i-1]-h[i])
print(hdf)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = [int(input()) for _ in range(n)]
h.sort()

ans = 10**10
for i in range(n-k+1):
  ans = min(ans, h[i+k-1]-h[i])
  
print(ans)

Submission status: Accepted

Solution code:
import itertools
import math
import fractions
import functools
n, k = map(int, input().split())
h = []
for i in range(n):
    h.append(int(input()))

h.sort()
subs = []
for i in range(1,n):
    subs.append(h[i]-h[i-1])

amount = [0]*(n)
sums = 0
for i in range(0,len(subs)):
    sums += subs[i]
    amount[i+1] = sums


minimum = 10**10
for i in range(k-1,n):
    minimum = min(minimum,amount[i]-amount[i-k+1])

print(minimum)

Submission status: Accepted

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

h_list = []
for _ in range(n):
    h = int(input())
    h_list.append(h)

h_list.sort()

ans = 10000000000
for i in range(n-k+1):
    tmp = abs(h_list[i]-h_list[i+k-1])
    if ans > tmp:
        ans = tmp

print(ans)

Submission status: Accepted

Solution code:
#AtCorder Begginer Contest 161 Christmas Eve
import numpy as np
N,K= map(int, input().split())
Tree_List= [int(input()) for i in range(N)]
Tree_List=np.array(sorted(Tree_List))
Answer=min(Tree_List[K-1:]-Tree_List[:-(K-1)])
print(Answer)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = sorted([int(input()) for i in range(n)])
ans = 1e9
for i in range(n - k + 1):
  ans = min(ans, h[i + k - 1] - h[i])
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = [0]*n
for i in range(n):
    h[i] = int(input())
h.sort()
ans = float("inf")
for i in range(n-k+1):
    res = abs(h[i] - h[i+k-1])
    ans = min(ans, res)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = []
for i in range(n):
    h.append(int(input()))

h.sort()

min_diff = 10**9
for i in range(n-k+1):
    diff = h[i+k-1] - h[i]
    min_diff = min(diff, min_diff)

print(min_diff)

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline


def main():
    N, K = map(int, input().split())
    h = [0] * N
    for i in range(N):
        h[i] = int(input())
    h.sort()

    ans = float("inf")
    for i in range(N - (K - 1)):
        diff = h[i + (K - 1)] - h[i]
        if diff < ans:
            ans = diff

    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=[]
for i in range(n):
    h.append(int(input()))
h.sort()
mi=h[len(h)-1]
for i in range(n-k+1):
    if h[i+k-1]-h[i]<mi:
        mi=h[i+k-1]-h[i]
print(mi)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
a = [0]*n
for i in range(n):
  a[i] = int(input())

a.sort()

ans = a[-1]-a[0]
for i in range(n-k+1):
  if ans > a[i+k-1]-a[i]:
    ans = a[i+k-1]-a[i]

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
s = [int(input()) for i in range(n)]

s.sort()
d = []
for i in range(n-1):
    d.append(s[i+1]-s[i])


ans = 0
for i in range(k-1):
    ans += d[i]

tmp = ans
for i in range(n-k):
    tmp -= d[i]
    tmp += d[i+k-1]
    ans = min(tmp,ans)

print(ans)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=[]
for i in range(n):
  h.append(int(input()))
h.sort()  
res=10**100
for i in range(0,n-k+1):
  tmp=h[i+k-1]-h[i]
  if tmp<res:
    res=tmp
print(res)

Submission status: Accepted

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

h = []
for i in range(N):
    h.append(int(input()))

h.sort()

minDistance = 10 ** 9
for i in range(0, N - K + 1):
    if h[i + K - 1] - h[i] < minDistance:
        minDistance = h[i + K - 1] - h[i]

print(minDistance)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
H=[int(input()) for _ in range(n)]

H.sort()
res=10**9+1

for i in range(n-k+1):
	res=min(res,H[i+k-1]-H[i])

print(res)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = [int(input()) for i in range(n)]
h.sort()
print(min([h[i+k-1]-h[i] for i in range(n-k+1)]))

Submission status: Accepted

Solution code:
N,K,*H = map(int,open(0).read().split())
H = sorted(H)

ans = 10 ** 9
for i in range(N-K+1):
  diff = H[i + K - 1] - H[i]
  if diff < ans:
    ans = diff
    
print(ans)

Submission status: Accepted

Solution code:
N,K = map(int, input().split())
h = []
for i in range(N):
    h.append(int(input()))
h.sort()
res = 10**9
for i in range(N-K+1):
    if res > h[i+K-1]-h[i]:
        res = h[i+K-1]-h[i]
print(res)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
h = []
for i in range(n):
    hi = int(input())
    h.append(hi)
h.sort()

min = 10**100
for i in range(n-k+1):
    if min > h[k+i-1]-h[i]:
        min = h[k+i-1]-h[i]

print(min)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
hhh = sorted([int(input()) for _ in range(n)])
print(min(hhh[i + k - 1] - hhh[i] for i in range(n - k + 1)))

Submission status: Accepted

Solution code:
from collections import deque
d = deque()
n,k = map(int,input().split())
l = [0]*n
for i in range(n):
  l[i] = int(input())
l.sort()
for i in range(k-1):
  d.append(l[i])
mini = 10**9
for i in range(k-1,n):
  x = d.popleft()
  y = l[i]
  mini = min(mini,y-x)
  d.append(y)
print(mini)

Submission status: Accepted

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

def main():
    N, K = map(int, readline().rstrip().split())
    H = [int(readline()) for _ in range(N)]
    H.sort()
    ans = 10 ** 10
    for i in range(N-K+1):
        ans = min(ans, H[i+K-1]-H[i])

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
h = list()
for i in range(N):
    h.append(int(input()))
h.sort()
ans = 10**9+1
for i in range(N-K+1):
    ans = min(ans, abs(h[i]-h[i+K-1]))

print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
ls = [int(input()) for i in range(n)]
ls.sort()
a = 0
for j in range(n-k+1):
    if j ==0:
        a = ls[j+k-1] - ls[j]
    else:
        if ls[j+k-1] - ls[j] < a:
            a = ls[j+k-1] - ls[j]
print(a)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
try:
    from typing import List
except ImportError:
    pass


def solve(N: int, K: int, h: "List[int]"):
    h.sort()
    print(min(h[i + K - 1] - h[i] for i in range(N - K + 1)))


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    h = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, K, h)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n, k = [int(x) for x in input().split()]
h_list = sorted([int(input()) for _ in range(n)])

temp = h_list[k - 1] - h_list[0]
ans = temp
for i in range(k, n):
    temp = h_list[i] - h_list[i - k + 1]
    if ans > temp:
        ans = temp
print(ans)

Submission status: Accepted

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

import fractions
import copy
import bisect
import math
import numpy as np
import itertools
from itertools import combinations_with_replacement
#import math#数学的計算はこれでいける。普通に0.5乗しても計算可能
#w=input()
from operator import itemgetter
from sys import stdin
#input = sys.stdin.readline#こっちの方が入力が早いが使える時に使っていこう
from operator import mul
from functools import reduce
from collections import Counter
#from collections import deque

#input = stdin.readline


j=0
k=0
n=3
r=1
a=[0]
#n=int(input())
#r=int(input())
#print(M)
#A=int(input())
#B=int(input())
#print(N)
"1行1つの整数を入力を取得し、整数と取得する"


#number_list=list(map(int, input().split(" ")))#数字の時
#print(number_list)
"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#メモ
for i in number_list:#こっちの方がrage使うより早いらしい
    print(number_list[i-1])#

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'''
x=[]
y=[]
for i in range(N):
    x1, y1=[int(i) for i in input().split()]
    x.append(x1)
    y.append(y1)
print(x)
print(y)
"複数行に2数値を入力する形式 x座標とy座標を入力するイメージ"
'''

'''
mixlist=[]
for i in range(N):
    a,b=input().split()
    mixlist.append((int(a),b))
print(mixlist)
"複数行にintとstrを複合して入力するやつ，今回はリスト一つで処理している"
'''

'''
#array=[input().split()for i in range(N)]
#print(type(array[0][0]))
#print(array)
"正方行列にstr型の値を入力"
'''

#brray=[list(map(int, input().split(" ")))for i in range(N)]
#print(type(brray[0][0]))
#print(brray)
'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"
#以下に別解を記載
#N, M = [int(i) for i in input().split()]
'''
table = [[int(i) for i in input().split()] for m in range(m)]

print(type(N))
print(N)
print(type(M))
print(M)

print(type(table))
print(table)
'''




#s=input()
#a=[int(i) for i in s]
#print(a[0])
#print([a])
#単数値．桁ごとに分割したい．入力と出力は以下の通り
#イメージとして1桁ごとにリストに値を入れているかんじ
#intを取ると文字列分解に使える
'''
入力
1234
出力
1
[[1, 2, 3, 4]]
'''




'''
word_list= input().split(" ")
print(word_list[0])
"連続文字列の入力"
"qw er ty とかの入力に使う"
"入力すると空白で区切ったところでlistの番号が与えられる"
'''



'''
A, B, C=stdin.readline().rstrip().split()#str style 何個でもいけることが多い
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''


#a= stdin.readline().rstrip()
#print(a.upper())
"aという変数に入っているものを大文字にして出力"


#a,b=map(int, input().split())  #int style 複数数値入力　「A B」みたいなスペース空いた入力のとき

#なんかうまく入力されるけど
#a=[[int(i) for i in 1.strip()]for 1 in sys.stdin]
#a = [[int(c) for c in l.strip()] for l in sys.stdin]]
#print(a)
#複数行の数値を入力して正方行列を作成


##############################################################################################
##############################################################################################
#under this line explains example calculation



'''
コンビネーションの組み合わせの中身を出力する形式
for i in itertools.combinations(brray, 2)
combinationsをpermutationsにすれば順列になる
今回なら(abc133B)
入力
1 2
5 5
-2 8
出力
[[1, 2], [5, 5], [-2, 8]]
もちろん一次元リストでも使えるし
何よりiもリストのように使えるので便利
'''

#nCr combination
'''
def cmb(n,r):
    #When n < r , this function isn't valid
    r= min(n-r,r)
    #print(n,r)
    if r == 0: return 1
    over = reduce(mul, range(n, n-r, -1))
    #flochart mul(n,n-1)=x
    #next     mul(x,n-2)........(n-r+1,n-r)
    #mul read a,b and returns a*b

    under = reduce(mul, range(1, r+1))
    #print(over, under)
    #reduce is applied mul(1,2)=2
    #next   mul(2,3)=6
    #next   mul(6,4)=4.........last(r!,r+1)=r+1!

    return over // under
    #// is integer divide
    #calc example 5C2
    #over=5*4*3
    #under=3*2*1
a = cmb(n, r)
#print(a)
'''

'''
import itertools
from itertools import combinations_with_replacement

combinationについて
以下の違いを意識しよう
combinations() p, r 長さrのタプル列、ソートされた順で重複なし

combinations_with_replacement() p, r 長さrのタプル列、ソートされた順で重複あり


使用例 　　　　　　　　　　　                  出力　　
combinations('ABCD', 2)　　　　　　　　　　　　AB AC AD BC BD CD

combinations_with_replacement('ABCD', 2)　　 AA AB AC AD BB BC BD CC CD DD
'''



'''
#集計
#example
#a=[2,2,2,3,4,3,1,2,1,3,1,2,1,2,2,1,2,1]
#a=Counter(a)
for i in a.most_common(n):print(i)
#most_common()メソッドは、出現回数が多い要素順にCounterオブジェクトを並び替えます。
#引数にint型の数字nを設定した場合は、出現回数が高い上位ｎ個の要素を返します。
#何も設定しなければ、コンテナ型にあるすべての要素を出現回数の順番に並び替えたタプル型オブジェクトを返します。
#out put
#(2, 8)
 #(1, 6)
#(3, 3)
#(4, 1)
'''


#二部探索(binary search)
#A = [1, 2, 3, 3, 3, 4, 4, 6, 6, 6, 6]
#print(A)
#index = bisect.bisect_left(A, 5) # 7 最も左(前)の挿入箇所が返ってきている
#A.insert(index, 5)
#print(index)
#print(A)
'''
bisect.bisect_left(a, x, lo=0, h=len(a))
引数
a: ソート済みリスト
x: 挿入したい値
lo: 探索範囲の下限
hi: 探索範囲の上限
(lo, hiはスライスと同様の指定方法)
bisect_leftはソートされたリストaに対して順序を保ったままxを挿入できる箇所を探索します。leftが示す通り、aにすでにxが存在している場合は、挿入箇所は既存のxよりも左側になります。また、lo, hiを指定することで探索範囲を絞り込むことも可能です。デフォルトはaの全体が探索対象です。
'''

'''
素数の判定
'''


def is_prime(n):
    if n == 1: return False

    for k in range(2, int(np.sqrt(n)) + 1):
        #sqrt(n)+1以上は考えて約数はないので却下
        if n % k == 0:
            return False
            #割り切れたらFalse
    return True


'''
npのmaxとmaximumの違い
xs = np.array([1, -2, 3])
np.max(xs, 0)
この出力は3となります．[1, -2, 3]と0の4つの数字のうち，最も大きい値を出力します．

一方で，[max(1, 0), max(-2, 0), max(3, 0)]を出力したい時があります．
その時は，numpyのmaximum関数を用います．

xs = np.array([1, -2, 3])
np.maximum(xs, 0)  # [1, 0, 3]

'''

def factorial(x, mod=10**9+7):
    # x!
    # 階乗
    # ex) factorial(5) = 120
    tmp = 1
    for i in range(1, x+1):
        tmp = (tmp * i) % mod
    return tmp
    '''
    Basically, when you do a**d % n, you actually have to calculate a**d, which could be quite large.
    But there are ways of computing a**d % n without having to compute a**d itself, and that is what pow does.
    '''


########################################################################
########################################################################
#b2=a[:]  #1次元のときはコピーはこれで良い
#print(b2)

#a= [[0]*3 for i in range(5)] #2次元配列はこう準備、[[0]*3]*5だとだめ
#b3=copy.deepcopy(a)  #2次元配列はこうコピーする
#print(b3)

def main():

    w=1
    j=0
    k=0
    #n=int(input())
    #r=int(input())
    #dp= [[0]*3 for i in range(5)]#列　行
    #dp用の0の入ったやつ
    #dp= [[0]*(w+1) for i in range(n+1)]#0からwまでのw+1回計算するから
    #print(dp)＃初期条件が入る分計算回数+1列分必要(この場合は判断すべきものの数)
    DP = np.zeros(w+1, dtype=int)#これでも一次元リストが作れる
    exdp=np.zeros((3,4)) # ３×４の２次元配列を生成。2次元ならこう
    #dtypeは指定しないとfloatになる
    #for i in range(n):#ちょっとした入力に便利
    #    a, b = map(int, input().split())
        #dp[i][0] += [a]
        #これだとintとlistをつなぐことになって不適
    #    dp[i] += [a]
    #    dp[i] += [b]
        #これはうまくいく
        #やり方はいろいろあるということ
    #print(dp)

    h=[]
    d=[]
    "1行1つの整数を入力を取得し、整数と取得する"
    n,k=map(int, input().split(" "))#数字の時
    for i in range(n):
        c=int(input())
        h +=[c]

    h.sort()
    #print(h)
    for i in range(n-k+1):
        d.append(h[i+k-1]-h[i])
    print(min(d))
    #print(number_list)
    "12 21 332 とか入力する時に使う"
    "1行に複数の整数の入力を取得し、整数として扱う"
    #brray=[list(map(int, input().split(" ")))for i in range(N)
    #print(brray)


    #s=input()
    #a=[int(i) for i in s]#int取るとstrでも行ける
    #print(a)
    '''
    入力
    1234
    出力
    [1, 2, 3, 4]
    '''
    pin_l=["x" for i in range(10)]#内包表記に慣れろ
    #print(pin_l)

    ls = ["a", "b", "c", "d", "e"]


    #print(ls[2:5])
    #スライスでの取得

    #print(ls[:-3])
    #一番左端から右から3番目より左まで取得

    #print(ls[:4:2])
    #スライスで1個飛ばしで取得
    #ないときは左端スタート
    #始点のインデックス番号 : 終点のインデックス番号 : スキップする数+1
    #print(ls[::2])
    '''
    lsというリストの場合に、1つ飛びの値を取得したい場合には
    ls[::2]
    のようにします。こうすると、
    ["a", "c", "d"]と出力される
    '''

if __name__ == "__main__":
    main()