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:
# -*- 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)

'''
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv...\xaf\xb0...
lowercase = 'abcdefghijklmnopqrstuvwxyz'
octdigits = '01234567'
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU...
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
whitespace = '\t\n\x0b\x0c\r '
'''
'''
引数endに任意の文字列を指定すると、その文字列が改行の代わりに最後に挿入される。例えば連続するprint()の出力を改行なしで単純に連結したい場合は空文字列''を指定すればよい。

print('abc', end='---')
print('xyz')
# abc---xyz

print('abc', end='')
print('xyz')
# abcxyz
source: print_basic.py
なお、デフォルトで改行されるのは引数endのデフォルト値が改行文字'\n'に設定されているから。
'''

def main():
    n=3
    steps=0
    state=0
    w=1
    j=0
    k=0
    #lenを変数に置くと事故るから注意
    #n=int(input())
    #a,b=input().split(" ")#a,bがともに文字列のとき
    n,k=map(int, input().split(" "))
    h=[]
    d=[10**9]*n
    for i in range(n):
        h.append(int(input()))
    h.sort()
    for j in range(n-k+1):
        #print(j)
        d[j]=h[j+k-1]-h[j]
    print(min(d))
    #mapでとってもstrで変換すればappend可能
    #s=input()
    #a=[i for i in s]#int(i)にすれば数字も行ける
    #nl=list(map(int, input().split(" ")))#数字の時
    #print(a)
    #brray=[list(map(int, input().split(" ")))for i in range(N)]
    #print(brray)


    #for i in range(1,n+1,2):#これで1個飛ばしループになる
    # pass
     #print(i)

    l = ['aaa', 'bbb', 'ccc']
    x=l.index('aaa')#ある要素のインデックス番号を取得
    #s = ''.join(l)
    #s = " ".join(map(str,a))#スペースを空ける時はこう
    #print(s)
    # aaabbbccc

    #if state in known_states and not flag: # state => 2 steps => 5
        #こうやってある要素がリストの中にあるか探すのか
    #print(f'steps: {steps}, state: {state}')
    #こう書いてあるとデバックしやすい

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


    #brray=[list(map(int, input().split(" ")))for i in range(N)
    #print(brray)



    '''
    入力
    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()

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(ans, h[i+K-1]-h[i])
print(ans)

Submission status: Accepted

Solution code:
N,K,*H=map(int,open(0).read().split())
ans=10**9
H.sort()
i=0
while i+K-1<N:
    ans=min(ans,H[i+K-1]-H[i])
    i+=1
print(ans)

Submission status: Accepted

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

def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2
    # ここで分割を行う
    left = arr[:mid]
    right = arr[mid:]

    # 再帰的に分割を行う
    left = merge_sort(left)
    right = merge_sort(right)

    # returnが返ってきたら、結合を行い、結合したものを次に渡す
    return merge(left, right)


def merge(left, right):
    merged = []
    l_i, r_i = 0, 0

    # ソート済み配列をマージするため、それぞれ左から見ていくだけで良い
    while l_i < len(left) and r_i < len(right):
        # ここで=をつけることで安定性を保っている
        if left[l_i] <= right[r_i]:
            merged.append(left[l_i])
            l_i += 1
        else:
            merged.append(right[r_i])
            r_i += 1

    # 上のwhile文のどちらかがFalseになった場合終了するため、あまりをextendする
    if l_i < len(left):
        merged.extend(left[l_i:])
    if r_i < len(right):
        merged.extend(right[r_i:])
    return merged
h=merge_sort(h)
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 = [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 = [int(input()) for _ in range(n)]
h.sort()
m = 10**10
for i in range(n-k+1):
    b = h[i]
    a = h[i+k-1]
    if a - b < m:
        m = a - b

print(m)

Submission status: Accepted

Solution code:
n,k=map(int,input().split())
h=[int(input()) for i in range(n)]
h.sort()
m=10**10
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 = [0]*n
for i in range(n):
    h[i] = int(input())

h = sorted(h)
m = 10**10
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 = []

for _ in range(n):
    tmp = int(input())
    h.append(tmp)

h.sort()

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

Submission status: Accepted

Solution code:
# For taking integer inputs.
def inp():
    return(int(input()))


# For taking List inputs.
def inlist():
    return(list(map(int, input().split())))


# For taking string inputs. Actually it returns a List of Characters, instead of a string, which is easier to use in Python, because in Python, Strings are Immutable.
def instr():
    s = input()
    return(list(s[:len(s)]))


# For taking space seperated integer variable inputs.
def invr():
    return(map(int, input().split()))


N, K = invr()
A = []
for i in range(N):
    A.append(inp())
A = sorted(A)
res = A[N-1] - A[0]
for i in range(N-K+1):
    d = A[i+K-1] - A[i]
    res = min(d, res)
print(res)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
t=[0]*N
for i in range(N): t[i]=int(input())
t.sort(key=int)
ans=10**10
for i in range(N-K+1): ans=min(ans,t[i+K-1]-t[i])
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


#############
# Constants #
#############

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

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,K = IL()
T = ILs(N)

T.sort()

print(min( T[i+K-1]-T[i] for i in range(N-K+1)))

Submission status: Accepted

Solution code:
N, K = map(int, input().split())
H = [int(input()) for _ 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 = map(int, input().split())
A = sorted([int(input()) for i in range(N)])
B = [A[i-1]-A[i-K] for i in range(K, N+1)]
print(min(B))

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()


def main():
    N, K = map(int, input().split())
    h = [int(input()) for _ in range(N)]
    h.sort()
    cand = 10**10
    for i in range(N - K + 1):
        cand = min(cand, h[i + K - 1] - h[i])
    print(cand)





if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
## C - Christmas Eve
N, K = map(int, input().split())
H = sorted([int(input()) for i in range(N)])
rt = 10**9
for i in range(0,N-K+1):
    rt = H[K - 1 + i] - H[i] if rt > H[K - 1 + i] - H[i] else rt
print(rt)

Submission status: Accepted

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

h.sort()
result = 10**9+1
for i in range(N-K+1):
    a = abs(h[i] - h[i+K-1])
    if a < result:
        result = a

print(result)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n,k = map(int, input().split())
h = list(sorted([int(input()) for i in range(n)]))
h.sort()
ans = h[n-1]+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=[int(input()) for _ in range(n)]
h.sort()
ans=float('inf')
for i in range(n-k+1):
    tmp=h[i+k-1]-h[i]
    ans=min(tmp,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.sort()
ans = 1000000000
for i in range(N-K+1):
    tmp = H[K-1+i] - H[i]
    if tmp < ans:
        ans = tmp
print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

ans = 1e+12
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())
High = [int(input()) for _ in range(N)]
High.sort()
ans = float('inf')
for i in range(N - K + 1):
    ans = min(High[K + i - 1] - High[i], ans)

print(ans)

Submission status: Accepted

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

h.sort(reverse=True) 

out = 10**9

L = 0
R = K-1
while R<=N-1:
    D = h[L]-h[R]
    if out > D:
        out = D
    L+=1
    R+=1
print(out)

Submission status: Accepted

Solution code:
import itertools
import math
import fractions
import functools
import copy

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

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

print(minimum)

Submission status: Accepted

Solution code:
# C - Christmas Eve

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

h.sort()
diffs = []
for i in range(K-1, N):
    diffs.append(h[i] - h[i-(K-1)])

print(min(diffs))

Submission status: Accepted

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

Submission status: Accepted

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

min_d = 10**9
for i in range(K-1,N):
  d=h[i]-h[i-(K-1)]
  if d<min_d:
    min_d=d
print(min_d)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = []
for i in range(n):
    h.append(int(input()))
h.sort()
ans = 10 ** 10
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()
min = float("INF")
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())
hn = [int(input()) for _ in range(n)]
hn.sort()
ans = 10**9
for i in range(n-k+1):
    ans = min(ans, hn[i+k-1] - hn[i])
print(ans)

Submission status: Accepted

Solution code:
n,k = map(int,input().split())
h_list = [int(input()) for nesya in range(n)]
h = sorted(h_list)
s = 10**9
for i in range(n-k+1):
  t = h[i+k-1] - h[i]
  if s > t:
    s = t
print(s)

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 = map(int, input().split())
h = []
for i in range(n):
    h.append(int(input()))

h.sort()

ret = 10 ** 100

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

print(ret)

Submission status: Accepted

Solution code:
N, K = map(int, input().split(' '))
heights = sorted([int(input()) for _ in range(N)])
print(min((_max - _min for _min, _max in zip(heights, heights[K - 1:]))))

Submission status: Accepted

Solution code:
N, K = map(int, input().split(' '))
heights = sorted([int(input()) for _ in range(N)])
print(min([_max - _min for _min, _max in zip(heights, heights[K - 1:])]))

Submission status: Accepted

Solution code:
N,K=map(int,input().split())
h=[int(input()) for _ in range(N)]
h.sort()
ans=0
for i in range(N-K+1):
    if i==0:
        ans=h[i+K-1]-h[i]
    else:
        if ans>h[i+K-1]-h[i]:
            ans=h[i+K-1]-h[i]
print(ans)

Submission status: Accepted

Solution code:
#  C. Christmas Eve
# https://atcoder.jp/contests/abc115/tasks/abc115_c

from heapq import heapify, heappop, heappush

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

stack = []

for i in range(k):
  heappush(stack, H[i])

r = stack[-1] - stack[0] 

for i in range(k, n):
  heappop(stack)
  heappush(stack, H[i])
  r = min(r, stack[-1] - stack[0])

print(r)

Submission status: Accepted

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

L = []

for i in range(n - k + 1):
    L.append(a[i + k - 1] - a[i])

print(min(L))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
#%% for atcoder uniittest use
import sys
input= lambda: sys.stdin.readline().rstrip()
def pin(type=int):return map(type,input().split())
def tupin(t=int):return tuple(pin(t))
#%%code
def resolve():
    N,K=pin()
    h=[int(input()) for i in range(N)]
    h.sort()
    temp=10**9+1
    for i in range(N-K+1):
        temp=min(temp,h[i+K-1]-h[i])
    print(temp)
#%%submit!
resolve()

Submission status: Accepted

Solution code:
import itertools
import sys

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

h = sorted(h)
cusum = [0] * n
for i in range(1, n):
    cusum[i] = cusum[i - 1] + h[i - 1]

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

print(m)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 6)


def input():
    return sys.stdin.readline()[:-1]


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

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 sys
input = sys.stdin.readline
n, k = [int(x) for x in input().split()]
h = [int(input()) for _ in range(n)]
h.sort()
ans = 10 ** 10
for i in range(n):
    if i + k - 1 >= n:
        break
    ans = min(ans, h[i + k - 1] - h[i])
print(ans)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()

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

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:
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(ans,h[i+k-1] - h[i])
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 = 1e+9
  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:
N, K = map(int,input().split())
h = []
INF = 2e9
for i in range (N):
  a = int(input())
  h.append(a)
h.sort()
ans = 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=[]
for i in range(n):
    h.append(int(input()))
h.sort()

ans=9999999999999
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 = tuple(map(int,input().split()))

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

h = sorted(h)

candidates = []
for i in range(n-k+1):
  candidates.append(h[i+k-1]-h[i])

print(min(candidates))

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:
N,K = map(int,input().split())
h = [int(input()) for _ in range(N)]
h.sort()
ans = 1e10
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
from collections import *

N, K = map(int, input().split())
h = [int(input()) for _ 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 = map(int, input().split())
h = list(int(input()) for _ in range(n))
h.sort()
ans = float("INF")
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())
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:
N, K = map(int, input().split())
h = [int(input()) for i in range(N)]

h.sort()
ans = float("inf")

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

print(ans)

Submission status: Accepted

Solution code:
import sys
import math
import bisect

def solve(A, m):
    n = len(A)
    min_val = 10 ** 18
    A.sort()
    for i in range(n):
        if i + m <= n:
            val = A[i+m-1] - A[i]
            min_val = min(min_val, val)
    return min_val

def main():
    n, m = map(int, input().split())
    A = []
    for i in range(n):
        A.append(int(input()))
    print(solve(A, m))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from itertools import permutations, accumulate, combinations, combinations_with_replacement
from math import sqrt, ceil, floor, factorial
from bisect import bisect_left, bisect_right, insort_left, insort_right
from copy import deepcopy
from operator import itemgetter
from functools import reduce
from fractions import gcd
import sys
def input(): return sys.stdin.readline().rstrip()
def I(): return int(input())
def Is(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def TIR(n): return [TI() for _ in range(n)]
def S(): return input()
def Ss(): return input().split()
def LS(): return list(input())
def SR(n): return [S() for _ in range(n)]
def SsR(n): return [Ss() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
sys.setrecursionlimit(10**6)
MOD = 10**9+7
INF = 10**18
# ----------------------------------------------------------- #

n, k = Is()
H = IR(n)
H.sort()
ans = INF
for i in range(n-k+1):
    hmax = H[i+k-1]
    hmin = H[i]
    ans = min(ans, hmax-hmin)
print(ans)

Submission status: Accepted

Solution code:
n, k = map(int, input().split())
h = sorted(int(input()) for _ in range(n))
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:
n, k = map(int, input().split())
h = [0] * n
for i in range(n):
    x = int(input())
    h[i] = x

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