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).

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)]))

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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)))

Solution (Python):
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)

Solution (Python):
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()

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):

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))  
    K = int(next(tokens))  
    h = [int(next(tokens)) for _ in range(N)]  
    solve(N, K, h)


if __name__ == '__main__':
    main()

Solution (Python):
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)

Solution (Python):

import sys

import fractions
import copy
import bisect
import math
import numpy as np
import itertools
from itertools import combinations_with_replacement


from operator import itemgetter
from sys import stdin

from operator import mul
from functools import reduce
from collections import Counter





j=0
k=0
n=3
r=1
a=[0]






"1行1つの整数を入力を取得し、整数と取得する"




"12 21 332 とか入力する時に使う"
"1行に複数の整数の入力を取得し、整数として扱う"

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

for i in number_list:
    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を複合して入力するやつ，今回はリスト一つで処理している"
'''

'''



"正方行列にstr型の値を入力"
'''




'''
入力
1 2
4 5
7 8
出力結果
[[1, 2], [4, 5], [7, 8]]
'''
"列数に関して自由度の高いint型の値を入力するタイプの行列"


'''
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)
'''











'''
入力
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()
print(A)
"リストではなく独立したstr型を入れるなら以下のやり方でOK"
'''




"aという変数に入っているものを大文字にして出力"

















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


'''
def cmb(n,r):
    
    r= min(n-r,r)
    
    if r == 0: return 1
    over = reduce(mul, range(n, n-r, -1))
    
    
    

    under = reduce(mul, range(1, r+1))
    
    
    
    

    return over // under
    
    
    
    
a = cmb(n, r)

'''

'''
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
'''



'''




for i in a.most_common(n):print(i)





 


'''









'''
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):
        
        if n % k == 0:
            return 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)  

'''

def factorial(x, mod=10**9+7):
    
    
    
    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.
    '''











def main():

    w=1
    j=0
    k=0
    
    
    
    
    
    
    DP = np.zeros(w+1, dtype=int)
    exdp=np.zeros((3,4)) 
    
    
    
        
        
    
    
        
        
    

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

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


    
    
    
    '''
    入力
    1234
    出力
    [1, 2, 3, 4]
    '''
    pin_l=["x" for i in range(10)]
    

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


    
    

    
    

    
    
    
    
    
    '''
    lsというリストの場合に、1つ飛びの値を取得したい場合には
    ls[::2]
    のようにします。こうすると、
    ["a", "c", "d"]と出力される
    '''

if __name__ == "__main__":
    main()

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

Solution (Python):
n, k = map(int, input().split())
li = [int(input())for _ in range(n)]
li.sort()
min_sa = 99999999999999999999999999999
for i in range(n-k+1):
    min_sa = min(abs(li[i]-li[i+k-1]), min_sa)
print(min_sa)

Solution (Python):
N, K = list(map(int,input().split()))
h = [None for _ in range(N)]
MIN = float('inf')
for i in range(N):
  h[i] = int(input())
H = sorted(h)
for i in range(N-(K-1)):
  if MIN >= H[i+(K-1)] - H[i]:
    MIN = H[i+(K-1)] - H[i]
print(MIN)

Solution (Python):
N, K = map(int, input().split())
H = sorted([int(input()) for _ in range(N)])
ans = 10**9

for i in range(0, N-K+1):
    prob_ans = H[i+K-1] - H[i]
    ans = min(ans, prob_ans)

print(ans)

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

Solution (Python):
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]





N, K =mi()
A = sorted([ii() for _ in range(N)])

tmp = float('inf')
for i in range(N-K+1):
    if A[i+K-1] - A[i] < tmp:
        tmp = A[i+K-1] - A[i]
print(tmp)

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

lh = list()
for i in range(N):
    lh.append(int(input()))

lh = sorted(lh)

ldes = list()
for i in range(N-K+1):
    ldes.append(lh[i+K-1] - lh[i])

print(min(ldes))

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

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

Solution (Python):
n,k,*L = map(int,open(0).read().split())
L.sort()

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

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

h.sort()

ans = 10000000000000000

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

print(ans)

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

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

Solution (Python):
n,k = map(int,input().split())
input_h = sorted([int(input()) for i in range(n)])

dp = [0]*((n-k)+1)
for i in range(((n-k)+1)):
    dp[i]=input_h[i+k-1]-input_h[i]
print(min(dp))

Solution (Python):


def main():
    *N, = map(int, open(0).read().split())
    h = N[2:]
    K = N[1]
    N = N[0]

    h.sort(reverse=True)
    ans = max(h) - min(h)
    for i in range(0, N - K + 1):
        d = h[i] - h[i + K -1]
        if d < ans:
            ans = d
    print(ans)


main()

Solution (Python):
N, K = map(int, input().split())
H = sorted([int(input()) for _ in range(N)])
l, r = 0, K-1
ans = 10**10
for _ in range(N-K+1):
    ans = min(ans, H[r]-H[l])
    l += 1
    r += 1
print(ans)

Solution (Python):
N, K = map(int, input().split())
h = [int(input()) for _ in range(N)]
h.sort(reverse=True)
mn = h[0]

for i in range(N-K+1):
    mn = min(mn, h[i] - h[K+i-1])
print(mn)

Solution (Python):
n,k=map(int,input().split())
h=sorted([int(input()) for _ in range(n)])
dis=[0]*(n)
bh=h[0]
for i,ah in enumerate(h[1:]):
    dis[i]=ah-bh
    bh=ah
s=sum(dis[:k-1])
ms=s
for i in range(k-1,n-1):
    s+=dis[i]-dis[i-k+1]
    ms=min(ms,s)
print(ms)

Solution (Python):
N,M = list(map(int,input().split()))
listA = []
for i in range(N):
    listA.append(int(input()))
listA.sort()
min_sum = float("INF")
for i in range(N-M+1):
    if min_sum > listA[i+M-1]-listA[i]:
        min_sum = listA[i+M-1]-listA[i]
print(min_sum)

Solution (Python):
import sys
input = sys.stdin.readline
n,m= map(int,input().split())
A = [ int(input()) for _ in range(n)]
a=sorted(A)
ans = 10 **10
for i in range(n-m+1):
    ans = min(abs(a[i+m-1] - a[i]),ans)
print(ans)

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

print(ans)

Solution (Python):

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

h.sort()

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

print(hmin)

Solution (Python):
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):
  ans = min(H[i+k-1]-H[i], ans)
print(ans)

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

Solution (Python):
n,k = map(int,input().split())
h = sorted([int(input()) for i in range(n)])
res = [0]*(n-k+1)
for i in range(n-k+1):
    res[i] = h[i+k-1]-h[i]
print(min(res))

Solution (Python):
N, K = map(int, input().split())
h = [int(input()) for _ in range(N)]
h.sort()
ans = h[-1] - h[0]

for i in range(K - 1, N):
    ans = min(ans, h[i] - h[i - K + 1])

print(ans)

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

trees.sort()
min_val = trees[k-1] - trees[0]
for i in range(1, n - k + 1):
    min_val = min(abs(trees[i+k-1] - trees[i]), min_val)
print(min_val)

Solution (Python):
N,K = map(int,input().split())
H_input = list()
ABS = float('inf')

for i in range(N):
    H_input.append(int(input()))
H_input.sort()


for i in range(N-K+1):
    
    if ABS > (H_input[i+K-1] - H_input[i]):
        
        ABS = H_input[i+K-1] - H_input[i]
        
print(ABS)

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

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

Solution (Python):
n,k=map(int,input().split())
 
 
h=list(int(input()) for _ in range(n))
h.sort()
result=10**9
 
i=0
while i+k-1<n:
  result=min(result,h[i+k-1]-h[i])
  
  i+=1
  
print(result)

Solution (Python):

import sys

INF = 10 ** 10
def solve(N: int, K: int, h: "List[int]"):
    l = sorted(h)

    res = INF
    for i in range(0, N):
        if i + K - 1 == N:
            break
        res = min(l[i + K - 1] - l[i], res)
    
    print(res)
    return



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

if __name__ == '__main__':
    main()

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

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

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

print(ans)

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions
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)

Solution (Python):



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


h = sorted(h)
min_ans = float('INF')
for i in range(N-K+1):
    tmp_max = h[i+K-1]
    tmp_min = h[i]
    min_ans = min(min_ans, tmp_max - tmp_min)


print(min_ans)

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

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

Solution (Python):
n,k = map(int,input().split())
H = sorted([int(input()) for i in range(n)])
ans = H[-1]

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

Solution (Python):
from sys import stdin


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    N, K = list(map(int,_in[0].split(' ')))  
    h_arr = []
    for i in range(N):
        _ = int(_in[i+1])  
        h_arr.append(_)
    
    h_arr.sort()
    cnt = float('inf')
    for i in range(0,N-K+1):
        cnt = min(cnt,abs(h_arr[i]-h_arr[i+K-1]))
    
    print(cnt)

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

h = []
ans = 10**9

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

h.sort()

for i in range(N-K+1):
    ans = min(h[i+K-1]-h[i], ans)


print(ans)

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

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

H=sorted(H)
ans=10**10
for i in range(N-K+1):
    hmin=H[i]
    hmax=H[i+K-1]
    ans=min(ans, hmax-hmin)
print(ans)

Solution (Python):
N,K=map(int,input().split())
L=[]
ans=float("inf")
for i in range(N):
	L.append(int(input()))
L=sorted(L)
for i in range(N-K+1):
	ans=min(ans,L[i+K-1]-L[i])
print(ans)

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

    hi = int(input())
    h.append(hi)

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

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

trees = []

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

trees.sort()
min_diff = 10**10
for j in range(n-k+1):
    diff = abs(trees[j] - trees[j+k-1])
    if diff < min_diff:
        min_diff = diff

print(min_diff)

Solution (Python):
n,k = map(int,input().split())
h = list(int(input()) for _ in range(n))
h = sorted(h)
m = 100000000000000
for i in range(n-k+1):
    m = min(m,h[i+k-1]-h[i])
print(m)

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

Solution (Python):
N, K = [int(x) for x in input().split()]
H = [int(input()) for _ in range(N)]

H.sort()

ans = float("inf")
for i in range(N - K + 1):
    ans = min(ans, abs(H[i] - H[i + K - 1]))

print(ans)

Solution (Python):
def resolve():
    n,k=map(int, input().split())
    l=[int(input()) for i in range(n)]
    l.sort()
    a=0
    ans=10**9
    for i in range(n-k+1):
        a=l[i+k-1]-l[i]
        ans=min(a,ans)
    print(ans)
resolve()

Solution (Python):
N, K = map(int, input().split())
H = [int(input()) for _ in range(N)]
H.sort()

ans = 10 ** 9
for i in range(N - K + 1):
    tmp = H[i + K - 1] - H[i]
    ans = min(ans, tmp)

print (ans)

Solution (Python):
from statistics import median


from fractions import gcd
from itertools import combinations 
from collections import deque
from collections import defaultdict
import bisect










import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    n,k = readInts()
    h = [int(input()) for _ in range(n)]
    ans = float("inf")
    h = sorted(h)
    
    for i in range(n-k+1):
        
        ans = min(ans,h[i+k-1] - h[i])
    print(ans)
if __name__ == '__main__':
  main()

Solution (Python):
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)

Solution (Python):
n,k = map(int, input().split())
h = sorted([int(input()) for _ in range(n)])
ans = float("inf")
for i in range(n-k+1):
    ans = min(ans,h[i+k-1]-h[i])
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
INF = float("inf")


def main():
    n, k = map(int, input().split())
    h = [int(input()) for _ in range(n)]
    h.sort()
    ans = INF
    for i in range(n - k + 1):
        diff = h[i + k - 1] - h[i]
        ans = min(ans, diff)
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 5 + 10)
def input(): return sys.stdin.readline().strip()

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


resolve()

Solution (Python):
N,K = map(int,input().split())
H = sorted([int(input()) for _ in range(N)])
cmin = 10**9+7
for i in range(N-K+1):
    cmin = min(cmin,H[i+K-1]-H[i])
print(cmin)

Solution (Python):
import sys
def main():
    input = sys.stdin.readline
    N,K=map(int, input().split())
    H=[int(input()) for _ in range(N)]

    H.sort()
    ans=10**12
    for i in range(N):
        if i+K-1 >= N: break
        ans = min(ans, H[i+K-1]-H[i])
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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):
    ans = min(ans, H[i+k-1]-H[i])
print(ans)

Solution (Python):
def main():
    N, K = (int(i) for i in input().split())
    H = [int(input()) for i in range(N)]
    H.sort()
    ans = 10**12
    for i in range(N-K+1):
        ans = min(ans, H[i+K-1] - H[i])
    print(ans)


if __name__ == '__main__':
    main()

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

Solution (Python):
import sys
import os
import math
import string

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, K = il()
    H = [ii() for _ in range(N)]
    H = sorted(H, reverse=True)
    cnt = len(H)-K+1
    ret = [0]*cnt
    for i in range(cnt):
        ret[i] = H[i] - H[i+K-1]
    print(min(ret))


if __name__ == '__main__':
    main()

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

l.sort()
ans=10**10
for i in range(k-1,len(l)):
    ans=min(ans,l[i]-l[i-k+1])

print(ans)

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

H = [0] * N
for i in range(N):
    H[i] = int(input())
H.sort()

d = H[K-1] - H[0]
for i in range(1, N-K+1):
    d = min(H[i+K-1] - H[i], d)
print(d)

Solution (Python):
N, K = map(int, input().split())
h = [int(input()) for i in range(N)]
dif = []

h.sort()

for i in range(N-K+1):
  dif.append(h[i+K-1] - h[i])
  
print(min(dif))

Solution (Python):
N, K = map(int, input().split())
H = [0] * N
for i in range(N):
    H[i] = int(input())
H.sort()

ans = H[K - 1] - H[0]
for i in range(K, N):
    ans = min(ans, H[i] - H[i - K + 1])
print(ans)

Solution (Python):
import sys
import numpy as np






input = sys.stdin.readline
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):
    ans = min(ans,h[i+K-1]-h[i])
print(ans)

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

Solution (Python):
N,K = map(int,input().split(" "))
H = sorted([int(input()) for _ in range(N)])
Min = 10**10
for i in range(K-1,len(H))[::-1]:
    Abs = H[i]-H[i-(K-1)]
    if Abs<Min:
        Min = Abs
print(Min)

Solution (Python):
n, k = map(int, input().split())
ls = []
for i in range(n):
    ls.append(int(input()))
ls.sort()
ls2 = []
for j in range(n - k + 1):
    a = ls[j + k - 1] -ls[j]
    ls2.append(a)
print(min(ls2))

Solution (Python):
n,k=map(int,input().split())
a=[int(input()) for i in range(n)]
c=sorted(a)
m=10**10
for x in range(n-k+1):
    m=min(m,c[x+k-1]-c[x])
print(m)

Solution (Python):
inf = 10**9+7
mod = 10**9+7
n,k = map(int, input().split())
a = [int(input()) for i in range(n)]
a.sort()
minh = inf
for i in range(n-k+1):
    minh = min(minh, a[i+k-1]-a[i])
print(minh)

Solution (Python):
N,K=map(int,input().split())
H=[int(input()) for i in range(N)]
H=sorted(H)
ans=10**10
for i in range(N-K+1):
  ans=min(ans,H[i+K-1]-H[i])
print(ans)

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

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

    h.sort()

    ans = min(ma - mi for mi, ma in zip(h, h[K - 1:]))
    print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
N , M = (map(int , input().split()))
tree = []
for i in range(N):
    tree.append(int(input()))
sort_tree = sorted(tree)
print(min([sort_tree[i+M-1] - sort_tree[i] for i in range(N-M+1)]))

Solution (Python):
n, k = map(int, input().split())
h = []
for i in range(n):
    h.append(int(input()))
hlis = sorted(h)
ans = float('inf')
for i in range(n-k+1):
    ans = min(ans, hlis[i+k-1] - hlis[i])
print(ans)

Solution (Python):
N,K=map(int, input().split())
H=[0]*N
for i in range(N):
  h=int(input())
  H[i]=h
  
H=sorted(H)
ans=10**9+7
for i in range(N-K+1):
  ans=min(ans, H[i+K-1]-H[i])
  
print(ans)

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

Solution (Python):
n,k=map(int,input().split())
L=sorted(list(int(input()) for i in range(n)))
num=10**9
for i in range(n-k+1):
    num=min(num,L[i+k-1]-L[i])
print(num)

Solution (Python):
def main():
    n, k = map(int, input().split())
    num_list = []
    for _ in range(n):
        num_list.append(int(input()))
    
    num_list.sort()

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

    print(min_count)

if __name__ == '__main__':
    main()

Solution (Python):
N, K = map(int, input().split())
H = [int(input()) for _ in range(N)]
H.sort()
ans = 10 ** 18
for i in range(N - K + 1):
    h1 = H[i]
    h2 = H[i + K - 1]
    ans = min(ans, h2 - h1)
print(ans)

Solution (Python):
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

n,k = map(int,readline().split())
lst1 = []
for i in range(n):
    lst1.append( int(readline()))
lst1.sort()
ans = 10**9
for i in range(n-k+1):
    ans = min(ans,abs(lst1[i+k-1]-lst1[i]))

print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) 
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    


class cumsum1d:  
    def __init__(self, ls: list):
        '''
        1次元リストを受け取る
        '''
        from itertools import accumulate
        self.ls_accum = [0] + list(accumulate(ls))

    def total(self, i, j):
        
        return self.ls_accum[j] - self.ls_accum[i]


MOD = 10**9 + 7
INF = 2**31  

from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  



N, K = read_ints()
H, = read_col(N)
H.sort()
ans = 10**10
for i in range(N):
    j = i + K - 1  
    if j >= N:
        continue
    ans = min(ans, H[j] - H[i])
print(ans)

Solution (Python):
n,k = map(int,input().split())
h = [int(input()) for _ in range(n)]
h.sort()
sa = 10**10
for i in range(n-k+1):
    ma = h[i+k-1]
    mi = h[i]
    sa = min(sa,ma-mi)
print(sa)

Solution (Python):
def solve():
    N, K  = map(int, input().split())
    H = sorted([int(input()) for _ in range(N)])
    ans = float("inf")
    for i in range(N-K+1):
        ans = min(ans, H[i+K-1]-H[i])
    print(ans)

if __name__ == '__main__':
    solve()

Solution (Python):

import sys
input= lambda: sys.stdin.readline().rstrip()
def pin(type=int):return map(type,input().split())
def tup(t=int):return tuple(pin(t))

def resolve():
    N,K=pin()
    H=[int(input()) for i in range(N)]
    H.sort()
    
    ans=1000000000
    for i in range(N-K+1):
        ans=min(H[i+K-1]-H[i],ans)
    print(ans)

resolve()

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

Solution (Python):
import sys
input = sys.stdin.readline

INF = float("inf")


def main():
    n, k = map(int, input().split())
    h = [int(input()) for _ in range(n)]
    h.sort()
    ans = INF
    for i in range(n - k + 1):
        ans = min(ans, h[i+k-1] - h[i])
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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))