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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)]
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

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

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

print(hmin)

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):
  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()
ans = 10**9+1
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 = 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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
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


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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 = 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)))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# Problem C - Christmas Eve

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

# initialization
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)

# output
print(min_ans)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
from sys import stdin


if __name__ == "__main__":
    _in = [_.rstrip() for _ in stdin.readlines()]
    N, K = list(map(int,_in[0].split(' ')))  # type:list(int)
    h_arr = []
    for i in range(N):
        _ = int(_in[i+1])  # type:int
        h_arr.append(_)
    # vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
    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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

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()
tmp = 1000000000
for i in range(0, n-k+1):
    tmp = min(tmp, abs(h[i]-h[i+k-1]))
print(tmp)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

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)
    #print(h)
    for i in range(n-k+1):
        #print(h[i+k-1],h[i])
        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 = [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:
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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

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

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)

Submission status: Accepted

Solution code:
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))

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 = H[K - 1] - H[0]
for i in range(K, N):
    ans = min(ans, H[i] - H[i - K + 1])
print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np

# import os
# path = os.getcwd()
# path = os.path.join(path,"input.txt")
# sys.stdin = open(path)

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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

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 = min(ma - mi for mi, ma in zip(h, h[K - 1:]))
    print(ans)


if __name__ == '__main__':
    main()

# import sys
# input = sys.stdin.readline
# 
# sys.setrecursionlimit(10 ** 7)
# 
# (int(x)-1 for x in input().split())
# rstrip()
#
# def binary_search(*, ok, ng, func):
#     while abs(ok - ng) > 1:
#         mid = (ok + ng) // 2
#         if func(mid):
#             ok = mid
#         else:
#             ng = mid
#     return ok

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


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

    def total(self, i, j):
        # もとの配列lsにおける[i,j)の中合計
        return self.ls_accum[j] - self.ls_accum[i]


MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/abc115/tasks/abc115_c
# maxとminが近い→ソートして端が近い
N, K = read_ints()
H, = read_col(N)
H.sort()
ans = 10**10
for i in range(N):
    j = i + K - 1  # K個選ぶ
    if j >= N:
        continue
    ans = min(ans, H[j] - H[i])
print(ans)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#%% for atcoder uniittest use
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))
#%%code
def resolve():
    N,K=pin()
    H=[int(input()) for i in range(N)]
    H.sort()
    #print(H)
    ans=1000000000
    for i in range(N-K+1):
        ans=min(H[i+K-1]-H[i],ans)
    print(ans)
#%%submit!
resolve()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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):
    if h[i+k-1] - h[i] < ans:
        ans = h[i+k-1] - h[i]
print(ans)

Submission status: Accepted

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

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):
    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 i in range(n)]
h.sort()
ans=10**18
for i in range(n-k+1):
  ans=min(h[i+k-1]-h[i],ans)
print(ans)

Submission status: Accepted

Solution code:
def main():
    N, K = (int(i) for i in input().split())
    ans = 10**12
    H = [int(input()) for i in range(N)]
    H.sort()
    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 = [int(input()) for i in range(N)]
h.sort()
ans = max(h) - min(h)
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=[int(input())for _ in range(n)]
h.sort()
print(min(h[i]-h[i-k+1] for i in range(k-1,n)))

Submission status: Accepted

Solution code:
def examA():
    N = I()
    ans = ((N+1)//2)/N
    print(ans)
    return

def examB():
    N, K = LI()
    H = [I()for _ in range(N)]
    H.sort()
    ans = inf
    for i in range(N-K+1):
        cur = H[i+K-1]-H[i]
        if ans>cur:
            ans = cur
    print(ans)
    return

def examC():
    ans = 0
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(readline())
def LI(): return list(map(int,readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examB()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Submission status: Accepted

Solution code:
def main():
    n, k = map(int, input().split())
    h = [int(input()) for _ in range(n)]
    h.sort()
    answer = float("inf")
    for i in range(n - k + 1):
        answer = min(answer, h[i + k - 1] - h[i])
    print(answer)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

N, K = lr()
H = np.array([ir() for _ in range(N)])
H.sort()
Hdiff = H[K-1:] - H[:-(K-1)]
answer = Hdiff.min()
print(answer)