You are a given an array $a$ of length $n$. Find a subarray $a[l..r]$ with length at least $k$ with the largest median.

A median in an array of length $n$ is an element which occupies position number $\lfloor \frac{n + 1}{2} \rfloor$ after we sort the elements in non-decreasing order. For example: $median([1, 2, 3, 4]) = 2$, $median([3, 2, 1]) = 2$, $median([2, 1, 2, 1]) = 1$.

Subarray $a[l..r]$ is a contiguous part of the array $a$, i. e. the array $a_l,a_{l+1},\ldots,a_r$ for some $1 \leq l \leq r \leq n$, its length is $r - l + 1$.


-----Input-----

The first line contains two integers $n$ and $k$ ($1 \leq k \leq n \leq 2 \cdot 10^5$).

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \leq a_i \leq n$).


-----Output-----

Output one integer $m$ — the maximum median you can get.


-----Examples-----

Input
5 3
1 2 3 2 1
Output
2
Input
4 2
1 2 3 4
Output
3


-----Note-----

In the first example all the possible subarrays are $[1..3]$, $[1..4]$, $[1..5]$, $[2..4]$, $[2..5]$ and $[3..5]$ and the median for all of them is $2$, so the maximum possible median is $2$ too.

In the second example $median([3..4]) = 3$.

Difficulty: HARD
Tags: Dynamic programming

Sorting

Data structures
Skill types: Dynamic programming

Sorting

Data structures

Starter code:

Solutions:
import sys
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = 0
r = n
while l < r:
	if l + 1 == r:
		try1 = r
		flag = 0
		tmp = 0
		grid = [0]
		for i in range(n):
			if a[i] >= try1:
				tmp += 1
			else:
				tmp -= 1
			grid.append(tmp)
		lowestprev = 0
		for i in range(k, n + 1):
			lowestprev = min(lowestprev, grid[i - k])
			if grid[i] - lowestprev > 0:
				flag = 1
				break
		if flag:
			l = r
		break
	try1 = (l + r) // 2
	flag = 0
	tmp = 0
	grid = [0]
	for i in range(n):
		if a[i] >= try1:
			tmp += 1
		else:
			tmp -= 1
		grid.append(tmp)
	lowestprev = 0
	for i in range(k, n + 1):
		lowestprev = min(lowestprev, grid[i - k])
		if grid[i] - lowestprev > 0:
			flag = 1
			break
	if flag:
		l = try1
	else:
		r = try1
print(l)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
lo = 0
hi = n + 1

def works(v):
	c = [1 if av >= v else -1 for av in a]
	s = [0]
	for i in range(len(c)):
		s.append(s[-1] + c[i])
	mins = 0
	for i in range(k, len(c) + 1):
		mins = min(mins, s[i - k])
		if s[i] - mins > 0:
			return True
	return False
while lo + 1 < hi:
	m = (lo + hi) // 2
	if works(m):
		lo = m
	else:
		hi = m
print(lo)


(N, K) = map(int, input().split())
A = list(map(int, input().split()))
ok = 1
ng = N + 1
while ng - ok > 1:
	c = ok + ng >> 1
	B = [1 if a >= c else -1 for a in A]
	cumB = [0]
	for b in B:
		cumB.append(cumB[-1] + b)
	mi = 0
	for (l, r) in zip(cumB, cumB[K:]):
		if mi > l:
			mi = l
		if r - mi > 0:
			break
	else:
		ng = c
		continue
	ok = c
print(ok)


from itertools import *

def check(x):
	b = [0] + [1 if xx >= x else -1 for xx in a]
	sum = list(accumulate(b))
	mx = -1000000000
	for i in range(k, n + 1):
		mx = max(mx + b[i], sum[i] - sum[i - k])
		if mx > 0:
			return True
	return False
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
(l, r) = (1, n)
while l <= r:
	mid = (l + r) // 2
	if check(mid):
		l = mid + 1
	else:
		r = mid - 1
print(l - 1)


def bSearch(l, r, func):
	r += 1
	while l < r:
		m = (l + r) // 2
		if func(m) == False:
			l = m + 1
		else:
			r = m
	return l

def checkPossible(med, a, n, k):
	diff = 0
	minDiff = [inf for _ in range(n)]
	minDiff[0] = 0
	res = -1
	for (i, x) in enumerate(a):
		if x >= med:
			diff += 1
		else:
			diff -= 1
		minDiff[i] = min(minDiff[i], diff)
		if i > 0:
			minDiff[i] = min(minDiff[i], minDiff[i - 1])
		l = i + 1 - k
		if l == 0 and diff >= 1:
			res = 1
			break
		if l - 1 >= 0 and diff - minDiff[l - 1] >= 1:
			res = 1
			break
	return res

def main():
	(n, k) = readIntArr()
	a = readIntArr()

	def func(med):
		if checkPossible(med, a, n, k) == -1:
			return True
		else:
			return False
	ans = bSearch(1, n, func) - 1
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()


import sys
input = sys.stdin.readline
from itertools import accumulate
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = 1
r = n + 1
while r > l + 1:
	median = (l + r) // 2
	b = [1 if i >= median else -1 for i in a]
	pref_sum = [b[0]]
	for i in range(1, n):
		pref_sum.append(pref_sum[i - 1] + b[i])
	ans = False
	if pref_sum[k - 1] > 0:
		ans = True
	else:
		mn = 0
		for i in range(k, n):
			mn = min(mn, pref_sum[i - k])
			if pref_sum[i] - mn > 0:
				ans = True
				break
	if ans:
		l = median
	else:
		r = median
print(l)


import collections

def solve():
	(n, k) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	r = n + 1
	l = 1
	while r - l > 1:
		m = (r + l) // 2
		b = [1 if i >= m else -1 for i in a]
		for i in range(1, len(b)):
			b[i] += b[i - 1]
		ans = False
		if b[k - 1] > 0:
			ans = True
		mm = 0
		for i in range(k, n):
			mm = min(mm, b[i - k])
			if b[i] - mm > 0:
				ans = True
				break
		if ans:
			l = m
		else:
			r = m
	print(l)
t = 1
while t > 0:
	t -= 1
	solve()


(n, k) = map(int, input().split())
a = [int(i) for i in input().split()]
l = 1
r = n + 1
while r - l > 1:
	mid = (r + l) // 2
	b = [1 if i >= mid else -1 for i in a]
	for i in range(1, len(b)):
		b[i] += b[i - 1]
	ans = False
	if b[k - 1] > 0:
		ans = True
	mn = 0
	for i in range(k, len(b)):
		mn = min(mn, b[i - k])
		if b[i] - mn > 0:
			ans = True
	if ans:
		l = mid
	else:
		r = mid
print(l)


import sys
input = sys.stdin.readline

def check(num):
	c = [0] * (n + 1)
	b = [0] * n
	mini = 10 ** 18
	maxi = -10 ** 19
	v = 0
	for i in range(n):
		if a[i] >= num:
			b[i] = 1
		else:
			b[i] -= 1
		v += b[i]
		c[i + 1] = v
		if i >= k - 1:
			mini = min(mini, c[i - k + 1])
			maxi = max(maxi, v - mini)
	if maxi > 0:
		return True
	return False
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
low = min(a)
high = max(a)
while low < high:
	mid = (low + high) // 2
	if check(mid):
		low = mid + 1
	else:
		high = mid - 1
if check(low):
	print(low)
else:
	print(low - 1)


import os, sys
from io import BytesIO, IOBase

def check(n, k, a, mid):
	a = list(map(lambda xx: xx >= mid, a))
	cul = sum(a[:k])
	if cul >= k // 2 + 1:
		return 1
	(mino, mine, pr) = (0, 10 ** 10, 0)
	for i in range(n - k):
		pr += a[i]
		cul += a[i + k]
		if i & 1:
			mino = min(mino, pr - (i + 1) // 2)
		else:
			mine = min(mine, pr - i // 2)
		if k + i & 1 and cul - min(mino, mine - 1) >= (k + i + 1) // 2 + 1 or (not k + i & 1 and cul - min(mino, mine) >= (k + i + 1) // 2 + 1):
			return 1
	return 0

def main():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	(hi, lo, ans) = (n, 1, 1)
	while hi >= lo:
		mid = (hi + lo) // 2
		if check(n, k, a, mid):
			lo = mid + 1
			ans = mid
		else:
			hi = mid - 1
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import bisect
from collections import deque
import io, os
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
if k == 1:
	print(max(arr))
	exit(0)

def judge(x):
	bigger = []
	num = 0
	for i in range(n):
		if arr[i] > x:
			bigger.append(2 * num - i)
			num += 1
	m = len(bigger)
	if m < k // 2:
		return False
	minimum = [0] * m
	minimum[0] = bigger[0]
	for j in range(1, m):
		minimum[j] = min(minimum[j - 1], bigger[j])
		if j >= k // 2 and bigger[j] >= minimum[j - k // 2]:
			return True
	return False
front = 0
rear = n
while front < rear:
	mid = (front + rear) // 2
	flag = judge(mid)
	if flag:
		front = mid + 1
	else:
		rear = mid
ans = front
print(ans)


import os
import sys
from io import BytesIO, IOBase
import math
import itertools
import bisect
import heapq

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(int(n))
	return l

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def maxPrimeFactors(n):
	maxPrime = -1
	while n % 2 == 0:
		maxPrime = 2
		n >>= 1
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			maxPrime = i
			n = n / i
	if n > 2:
		maxPrime = n
	return int(maxPrime)

def countcon(s, i):
	c = 0
	ch = s[i]
	for i in range(i, len(s)):
		if s[i] == ch:
			c += 1
		else:
			break
	return c

def lis(arr):
	n = len(arr)
	lis = [1] * n
	for i in range(1, n):
		for j in range(0, i):
			if arr[i] > arr[j] and lis[i] < lis[j] + 1:
				lis[i] = lis[j] + 1
	maximum = 0
	for i in range(n):
		maximum = max(maximum, lis[i])
	return maximum

def isSubSequence(str1, str2):
	m = len(str1)
	n = len(str2)
	j = 0
	i = 0
	while j < m and i < n:
		if str1[j] == str2[i]:
			j = j + 1
		i = i + 1
	return j == m

def maxfac(n):
	root = int(n ** 0.5)
	for i in range(2, root + 1):
		if n % i == 0:
			return n // i
	return n

def p2(n):
	c = 0
	while n % 2 == 0:
		n //= 2
		c += 1
	return c

def seive(n):
	primes = [True] * (n + 1)
	primes[1] = primes[0] = False
	for i in range(2, n + 1):
		if primes[i]:
			for j in range(i + i, n + 1, i):
				primes[j] = False
	p = []
	for i in range(0, n + 1):
		if primes[i]:
			p.append(i)
	return p

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def denofactinverse(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return pow(fac, m - 2, m)

def numofact(n, m):
	fac = 1
	for i in range(1, n + 1):
		fac = fac * i % m
	return fac

def chk(val):
	temp = [-1] * n
	for i in range(0, n):
		if l[i] >= val:
			temp[i] = 1
	pre = [temp[0]]
	for i in range(1, n):
		pre.append(pre[-1] + temp[i])
	mnl = 0
	if pre[k - 1] > 0:
		return True
	for i in range(k, n):
		mnl = min(mnl, pre[i - k])
		if pre[i] - mnl > 0:
			return True
	return False
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
(f, r) = (1, n + 1)
while r - f > 1:
	mid = (r + f) // 2
	if chk(mid):
		f = mid
	else:
		r = mid
print(f)


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

def checkMedianAtleastX(x):
	arr = [1 if i >= x else -1 for i in ls]
	prefix_sums = [0]
	for i in arr:
		prefix_sums.append(prefix_sums[-1] + i)
	sum_min = 1000000
	for i in range(k, n + 1):
		sum_min = min(sum_min, prefix_sums[i - k])
		if prefix_sums[i] > sum_min:
			return True
	return False

def binSearch(l, r):
	if l == r:
		return l
	if l + 1 == r:
		if checkMedianAtleastX(r):
			return r
		return l
	mid = (l + r) // 2
	if checkMedianAtleastX(mid):
		return binSearch(mid, r)
	return binSearch(l, mid - 1)
print(binSearch(1, 2 * 100000))


import os
import sys
from io import BytesIO, IOBase

def check(b, k):
	temp = 0
	for i in range(1, len(b)):
		b[i] += b[i - 1]
	if b[k - 1] > 0:
		return 1
	else:
		for i in range(k, len(b)):
			temp = min(temp, b[i - k])
			if b[i] > temp:
				return 1
	return 0

def main():
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	l = 1
	r = n + 1
	while r - l > 1:
		mid = (r + l) // 2
		b = [1 if item >= mid else -1 for item in A]
		ans = check(b, k)
		if ans:
			l = mid
		else:
			r = mid
	print(l)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin
from collections import Counter
from math import pow, sqrt, factorial, log10, log
from itertools import permutations, combinations, combinations_with_replacement
input = stdin.readline

def li():
	return list(map(int, input().split()))

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

def inp():
	return int(input())

def pr(n):
	return stdout.write(str(n) + '\n')
INF = float('inf')

def solve():
	(n, k) = mp()
	a = li()
	(l, r) = (1, n)
	while l < r:
		m = l + r + 1 >> 1
		b = [0] * (n + 1)
		for i in range(n):
			if a[i] >= m:
				b[i + 1] = 1
			else:
				b[i + 1] = -1
			b[i + 1] += b[i]
		(x, f) = (0, 0)
		for i in range(k, n + 1):
			x = min(x, b[i - k])
			if x < b[i]:
				f = 1
				break
		if f:
			l = m
		else:
			r = min(r - 1, m)
	print(l)
t = 1
for i in range(t):
	solve()


inf = 10 ** 16
(n, k) = map(int, input().split())
aa = list(map(int, input().split()))

def ok(q):
	cs = [0]
	mn = inf
	for a in aa:
		cs.append(cs[-1] - 1 if a < q else cs[-1] + 1)
	for i in range(k, n + 1):
		mn = min(mn, cs[i - k])
		if cs[i] - mn > 0:
			return True
	return False
(ct, r) = (0, n + 1)
while ct + 1 < r:
	m = (ct + r) // 2
	if ok(m):
		ct = m
	else:
		r = m
print(ct)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = [int(item) for item in input().split()]
l = 0
r = n + 1
while r - l > 1:
	mid = (l + r) // 2
	is_larger = []
	for item in a:
		if item >= mid:
			is_larger.append(1)
		else:
			is_larger.append(-1)
	cumsum = [0]
	for item in is_larger:
		cumsum.append(cumsum[-1] + item)
	cummin = [0]
	for item in cumsum[1:]:
		cummin.append(min(cummin[-1], item))
	ok = False
	for i in range(k, n + 1):
		if cumsum[i] - cummin[i - k] > 0:
			ok = True
			break
	if ok:
		l = mid
	else:
		r = mid
print(l)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 51, func=lambda a, b: a & b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

def find(x, l, k):
	n = len(l)
	pre = [0] * n
	for i in range(n):
		if l[i] >= x:
			pre[i] = 1
		else:
			pre[i] = -1
	ma = [0] * (len(l) + 1)
	rt = [0] * (len(l) + 1)
	for i in range(1, n + 1):
		rt[i] = rt[i - 1] + pre[i - 1]
		ma[i] = min(ma[i - 1], rt[i])
	for i in range(1, n + 1):
		if i - k < 0:
			continue
		q = rt[i] - ma[max(0, i - k)]
		if q > 0:
			return True
	return False
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
st = min(l)
end = max(l)
ans = st
while st <= end:
	mid = (st + end) // 2
	if find(mid, l, k) == True:
		ans = mid
		st = mid + 1
	else:
		end = mid - 1
print(ans)


import sys
from sys import stdin
(n, k) = map(int, stdin.readline().split())
a = list(map(int, stdin.readline().split()))
xl = 1
xr = n + 1
while xr - xl != 1:
	xm = (xl + xr) // 2
	b = [0]
	for i in range(n):
		if a[i] >= xm:
			b.append(1)
		else:
			b.append(-1)
	for i in range(len(b) - 1):
		b[i + 1] += b[i]
	nmin = 0
	flag = False
	for i in range(k, len(b)):
		nmin = min(nmin, b[i - k])
		if b[i] - nmin > 0:
			flag = True
			break
	if flag:
		xl = xm
	else:
		xr = xm
print(xl)


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def possible(a, k):
	mi = 0
	lo = {0: -1}
	total = 0
	for (i, diff) in enumerate(a):
		total += diff
		if total < mi:
			lo[total] = i
			mi = total
		elif total > mi:
			if total < 1:
				if i - lo[total - 1] >= k:
					return True
			elif i + 1 >= k:
				return True
	return False

def solve():
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	s = sorted(a)
	lo = 0
	hi = n
	while lo + 1 < hi:
		mid = (lo + hi) // 2
		val = s[mid]
		b = list([1 if x >= val else -1 for x in a])
		if possible(b, k):
			lo = mid
		else:
			hi = mid
	print(s[lo])
t = 1
for _ in range(t):
	solve()


from os import path
from io import BytesIO, IOBase
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, Counter, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

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

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('0')
file = 1

def ceil(a, b):
	return (a + b - 1) // b

def solve():
	(n, k) = mi()
	a = li()

	def check(x):
		c = [0] * n
		for i in range(n):
			if a[i] >= x:
				c[i] = 1
			else:
				c[i] = -1
		for i in range(1, n):
			c[i] += c[i - 1]
		if c[k - 1] > 0:
			return True
		mnx = 0
		for i in range(k, n):
			mnx = min(mnx, c[i - k])
			if c[i] > mnx:
				return True
		return False
	l = 1
	r = n
	while l <= r:
		mid = l + r >> 1
		if check(mid):
			ans = mid
			l = mid + 1
		else:
			r = mid - 1
	print(ans)
if file:
	if path.exists('tmp/input.txt'):
		sys.stdin = open('tmp/input.txt', 'r')
		sys.stdout = open('tmp/output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys, math
import io, os
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.buffer.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
mod = int(1000000000.0) + 7
(n, k) = mdata()
a = mdata()
(l, r) = (1, n)
while l <= r:
	mid = (l + r) // 2
	b = [1 if i >= mid else -1 for i in a]
	for i in range(1, n):
		b[i] += b[i - 1]
	m = 0
	ans = False
	for i in range(k - 1, n):
		if b[i] - m > 0:
			ans = True
			break
		m = min(m, b[i - k + 1])
	if ans:
		l = mid + 1
	else:
		r = mid - 1
out(r)


def proc1(m: int, arr: list) -> None:
	global cnt1
	global cnt2
	cnt1 = [0] * (n + 2)
	cnt2 = [0] * (n + 2)
	for i in range(1, n + 1):
		if arr[i] < m:
			cnt1[i] = cnt1[i - 1] - 1
		else:
			cnt1[i] = cnt1[i - 1] + 1
	for i in range(n, 0, -1):
		if arr[i] < m:
			cnt2[i] = max(0, cnt2[i + 1] - 1)
		else:
			cnt2[i] = cnt2[i + 1] + 1
	pass

def proc2(m: int, k: int, arr: list) -> bool:
	global cnt1
	global cnt2
	proc1(m, arr)
	for i in range(1, n + 1):
		if i + k > n + 1:
			break
		c1 = cnt1[i + k - 1] - cnt1[i - 1]
		c2 = cnt2[i + k]
		if c1 + c2 > 0:
			return True
	return False

def solve(n: int, k: int, arr: list) -> int:
	arr2 = arr[1:n + 1]
	arr2.sort()
	(l, r) = (1, n)
	while l + 1 < r:
		mid = (l + r) // 2
		median = arr2[mid - 1]
		if proc2(median, k, arr):
			l = mid
		else:
			r = mid - 1
	if proc2(arr2[r - 1], k, arr):
		return arr2[r - 1]
	else:
		return arr2[l - 1]
	pass
read = input().split()
n = int(read[0])
k = int(read[1])
read = input().split()
arr = [0] * (n + 2)
for i in range(1, n + 1):
	arr[i] = int(read[i - 1])
ans = solve(n, k, arr)
print(ans)
pass


import sys
import math
from collections import defaultdict, Counter, deque
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def find(m):
	pre = [0] * (n + 1)
	cur = 0
	for j in range(n):
		if a[j] < m:
			cur -= 1
		else:
			cur += 1
		if j >= k - 1:
			if cur - pre[j - k] > 0:
				return 1
		pre[j] = min(pre[j - 1], cur)
	return 0
for i in range(1):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	l = 1
	r = n
	while l <= r:
		mid = (l + r) // 2
		if find(mid):
			l = mid + 1
		else:
			r = mid - 1
	print(r)


from typing import List
import random

def is_a_solution(ptr_l: int, ptr_r: int, delta: int) -> bool:
	return delta > 0

def can_get_at_least(med: int, numbers: List[int], k: int) -> bool:
	delta = 0
	for idx in range(k):
		if numbers[idx] < med:
			delta -= 1
		else:
			delta += 1
	(ptr_l, ptr_r) = (0, k)
	if is_a_solution(ptr_l, ptr_r, delta):
		return True
	while True:
		while ptr_r < len(numbers) and numbers[ptr_r] >= med:
			ptr_r += 1
			delta += 1
		while ptr_r - ptr_l > k and numbers[ptr_l] < med:
			ptr_l += 1
			delta += 1
		if is_a_solution(ptr_l, ptr_r, delta):
			return True
		if ptr_r - ptr_l > k:
			ptr_l += 1
			delta -= 1
		else:
			if ptr_r == len(numbers):
				break
			ptr_r += 1
			delta -= 1
	return False

def can_get_with_sums(med: int, numbers: List[int], k: int) -> bool:
	signs = [1 if val >= med else -1 for val in numbers]
	prefix = [0] * (len(numbers) + 1)
	min_upto = [0] * (len(numbers) + 1)
	for (idx, sign) in enumerate(signs):
		prefix[idx + 1] = prefix[idx] + sign
		min_upto[idx + 1] = min(min_upto[idx], prefix[idx + 1])
	for idx in range(k, len(numbers) + 1):
		cur = prefix[idx]
		min_sub = min_upto[idx - k]
		candidate = cur - min_sub
		if candidate > 0:
			return True
	return False

def solve_mine(n, k, numbers):
	(l, r) = (0, n)
	best_median = None
	while l <= r:
		mid = (l + r) // 2
		if can_get_at_least(mid, numbers, k):
			best_median = mid
			l = mid + 1
		else:
			r = mid - 1
	return best_median

def solve_theirs(n, k, numbers):
	(l, r) = (0, n)
	best_median = None
	while l <= r:
		mid = (l + r) // 2
		if can_get_with_sums(mid, numbers, k):
			best_median = mid
			l = mid + 1
		else:
			r = mid - 1
	return best_median
(n, k) = tuple(map(int, input().split()))
numbers = list(map(int, input().split()))
print(solve_theirs(n, k, numbers))

class TestWithStupidChecker:

	def solve_simple(self, seq: List[int], k: int) -> int:
		ans = 0
		for beg in range(len(seq) - k + 1):
			for end in range(beg + k - 1, len(seq)):
				cur_seq = seq[beg:end + 1]
				medi_idx = (len(cur_seq) - 1) // 2
				medi = sorted(cur_seq)[medi_idx]
				ans = max(ans, medi)
		return ans

	def test_20_tests_n20_k5(self):
		n = 100
		k = 5
		for _ in range(20):
			seq = [random.randint(1, n + 1) for _ in range(n)]
			simple = self.solve_simple(seq, k)
			clever = solve_mine(n, k, seq)
			if simple != clever:
				raise AssertionError(f'seq: {seq}\nk: {k}\nsimple: {simple}\nclever: {clever}')

class TestWithSumsChecker:

	def test_n200000_k10000(self):
		n = 11
		k = 7
		for _ in range(2000000):
			seq = [random.randint(1, n + 1) for _ in range(n)]
			theirs = solve_theirs(n, k, seq)
			mine = solve_mine(n, k, seq)
			if theirs != mine:
				raise AssertionError(f'seq: {seq}\nk: {k}\ntheirs: {theirs}\nmine: {mine}')


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline()

def RL():
	return map(int, sys.stdin.readline().split())

def RLL():
	return list(map(int, sys.stdin.readline().split()))

def N():
	return int(input())

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

def print_list(l):
	print(' '.join(map(str, l)))

def judge(n, k, p):
	s = [0]
	for i in range(n):
		if a[i] >= p:
			s.append(s[-1] + 1)
		else:
			s.append(s[-1] - 1)
	t = 0
	for i in range(k, n + 1):
		t = min(t, s[i - k])
		if s[i] > t:
			return True
	return False
(n, k) = RL()
a = RLL()
(l, r) = (min(a), max(a) + 1)
while l < r:
	m = l + r >> 1
	if judge(n, k, m):
		l = m + 1
	else:
		r = m
print(l - 1)


import sys
input = sys.stdin.readline
(n, k) = map(int, input().split())
A = list(map(int, input().split()))
MIN = min(A)
MAX = max(A)
OK = MIN
NG = MAX + 1
seg_el = 1 << (n + 1).bit_length()

def update(n, x, seg_el):
	i = n + seg_el
	SEG[i] = x
	i >>= 1
	while i != 0:
		SEG[i] = max(SEG[i * 2], SEG[i * 2 + 1])
		i >>= 1

def getvalues(l, r):
	L = l + seg_el
	R = r + seg_el
	ANS = -1 << 30
	while L < R:
		if L & 1:
			ANS = max(ANS, SEG[L])
			L += 1
		if R & 1:
			R -= 1
			ANS = max(ANS, SEG[R])
		L >>= 1
		R >>= 1
	return ANS
while NG - OK > 1:
	mid = (OK + NG) // 2
	S = [0]
	for a in A:
		if a >= mid:
			S.append(S[-1] + 1)
		else:
			S.append(S[-1] - 1)
	SEG = [-1 << 30] * (2 * seg_el)
	for i in range(n + 1):
		SEG[i + seg_el] = S[i]
	for i in range(seg_el - 1, 0, -1):
		SEG[i] = max(SEG[i * 2], SEG[i * 2 + 1])
	for i in range(n + 1 - k):
		t = S[i]
		if getvalues(i + k, n + 2) > t:
			OK = mid
			break
	else:
		NG = mid
print(OK)


import math

def getint():
	return [int(i) for i in input().split()]

def getstr():
	return [str(i) for i in input().split()]

def solve():
	(n, k) = getint()
	a = getint()
	l = 1
	r = n + 1
	while r - l > 1:
		mid = (r + l) // 2
		b = [1 if i >= mid else -1 for i in a]
		for i in range(1, len(b)):
			b[i] += b[i - 1]
		ans = False
		if b[k - 1] > 0:
			ans = True
		mn = 0
		for i in range(k, len(b)):
			mn = min(mn, b[i - k])
			if b[i] - mn > 0:
				ans = True
		if ans:
			l = mid
		else:
			r = mid
	print(l)
solve()


(n, k) = map(int, input().split())
a = [int(x) for x in input().split()]
p = [0] * n
mx = [0] * n

def check(x):
	for i in range(n):
		cur = 1 if a[i] >= x else -1
		if i == 0:
			mx[i] = p[i] = cur
		else:
			p[i] = p[i - 1] + cur
			mx[i] = max(cur, mx[i - 1] + cur)
	for i in range(k - 1, n):
		if p[i] - p[i - k + 1] + mx[i - k + 1] > 0:
			return 1
	return 0
ans = 0
for j in range(20, -1, -1):
	ans += 1 << j
	if not check(ans):
		ans -= 1 << j
print(ans)


def isValid(A, k, x):
	n = len(A)
	B = [0 for x in range(n)]
	for i in range(n):
		B[i] = A[i]
		if B[i] >= x:
			B[i] = 1
		else:
			B[i] = -1
	prefix = [0 for x in range(n)]
	minPrefix = [0 for x in range(n)]
	prefix[0] = B[0]
	minPrefix[0] = B[0]
	sum = B[0]
	for i in range(1, n):
		sum += B[i]
		prefix[i] = sum
		minPrefix[i] = min(minPrefix[i - 1], prefix[i])
	temp = -554
	for i in range(n):
		if i + 1 < k:
			pass
		elif i + 1 == k:
			temp = max(temp, prefix[i])
		else:
			temp = max(temp, prefix[i])
			temp = max(temp, prefix[i] - minPrefix[i - k])
	if temp > 0:
		return True
	return False

def main(A, k):
	n = len(A)
	start = 0
	if n == 1:
		return A[0]
	end = n - 1
	C = sorted(A)
	ans = None
	while start <= end:
		mid = (start + end) // 2
		if isValid(A, k, C[mid]):
			ans = C[mid]
			start = mid + 1
		else:
			end = mid - 1
	return ans
(n, k) = map(int, input().split())
A = [int(i) for i in input().split()]
print(main(A, k))


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi, inf
from collections import deque, defaultdict
from bisect import bisect, bisect_left
from itertools import permutations as per
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(str(x) + '\n')
nCr = lambda x, y: f[x] * inv(f[y] * f[x - y] % N) % N
inv = lambda x: pow(x, N - 2, N)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
(n, k) = R()
a = L()
l = 1
r = n + 1
while r - l > 1:
	m = (l + r) // 2
	p = 0
	b = []
	for i in a:
		if i >= m:
			p += 1
		else:
			p -= 1
		b += (p,)
	ans = False
	mn = 0
	if b[k - 1] > 0:
		ans = True
	for i in range(k, n):
		mn = min(mn, b[i - k])
		if b[i] - mn > 0:
			ans = True
			break
	if ans:
		l = m
	else:
		r = m
print(l)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
inf = 10 ** 16
md = 10 ** 9 + 7
(n, k) = MI()
aa = LI()

def ok(m):
	cs = [0]
	for a in aa:
		if a < m:
			cs.append(cs[-1] - 1)
		else:
			cs.append(cs[-1] + 1)
	mn = inf
	for r in range(k, n + 1):
		mn = min(mn, cs[r - k])
		if cs[r] - mn > 0:
			return True
	return False
(l, r) = (0, n + 1)
while l + 1 < r:
	m = (l + r) // 2
	if ok(m):
		l = m
	else:
		r = m
print(l)


import sys
input = sys.stdin.buffer.readline
from collections import deque

def test(a, m):
	b = [1 if a[i] >= m else -1 for i in range(n)]
	valid_prefixes = deque()
	mx_sum = 0
	psum = [0] * (n + 1)
	for i in range(n):
		psum[i + 1] = psum[i] + b[i]
		if i + 1 >= k:
			while valid_prefixes and valid_prefixes[-1] > psum[i + 1 - k]:
				valid_prefixes.pop()
			valid_prefixes.append(psum[i + 1 - k])
			mx_sum = max(mx_sum, psum[i + 1] - valid_prefixes[0])
	return mx_sum > 0
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = 0
r = n
while l != r:
	m = (l + r + 1) // 2
	if test(a, m):
		l = m
	else:
		r = m - 1
print(l)


class BIT:

	def __init__(self, n):
		self.n = n
		self.bit = [0] * (n + 1)
		self.el = [0] * (n + 1)

	def sum(self, i):
		s = 0
		while i > 0:
			s += self.bit[i]
			i -= i & -i
		return s

	def add(self, i, x):
		self.el[i] += x
		while i <= self.n:
			self.bit[i] += x
			i += i & -i

	def get(self, i, j=None):
		if j is None:
			return self.el[i]
		return self.sum(j) - self.sum(i - 1)

	def lower_bound(self, x):
		w = i = 0
		k = 1 << self.n.bit_length()
		while k:
			if i + k <= self.n and w + self.bit[i + k] < x:
				w += self.bit[i + k]
				i += k
			k >>= 1
		return i + 1

def check(target):
	B = [int(a >= target) * 2 - 1 for a in A]
	cum = [0] * (N + 1)
	for i in range(N):
		cum[i + 1] = cum[i] + B[i]
	for i in range(N + 1):
		cum[i] += N + 1
	bit = BIT(N * 2 + 1)
	for i in range(K, N + 1):
		bit.add(cum[i - K], 1)
		if bit.sum(cum[i] - 1):
			return True
	return False
(N, K) = map(int, input().split())
A = list(map(int, input().split()))
(low, high) = (1, N + 1)
mid = (low + high) // 2
while high - low > 1:
	if check(mid):
		low = mid
	else:
		high = mid
	mid = (low + high) // 2
ans = low
print(ans)


from sys import stdin, stdout, setrecursionlimit
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, log2
from random import seed, randint
from datetime import datetime
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from collections import defaultdict as dd
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def def_value():
	return 0
(n, k) = mp()
a = lmp()
b = sorted(a)
(l, r) = (1, n + 1)
while l < r - 1:
	mid = (l + r) // 2
	x = mid
	tmp = a.copy()
	for i in range(n):
		if tmp[i] >= x:
			tmp[i] = 1
		else:
			tmp[i] = -1
	for i in range(1, n):
		tmp[i] += tmp[i - 1]
	flg = False
	if tmp[k - 1] > 0:
		flg = True
	mn = 0
	for i in range(n - k):
		mn = min(mn, tmp[i])
		if tmp[i + k] - mn > 0:
			flg = True
			break
	if flg:
		l = mid
	else:
		r = mid
print(l)


(N, K) = map(int, input().split())
A = list(map(int, input().split()))
(L, R) = (1, N)
while L < R:
	M = L + R + 1 >> 1
	B = [0] * (N + 1)
	for i in range(N):
		if A[i] >= M:
			B[i + 1] = 1
		else:
			B[i + 1] = -1
		B[i + 1] += B[i]
	X = 0
	F = 0
	for i in range(K, N + 1):
		X = min(X, B[i - K])
		if X < B[i]:
			F = 1
			break
	if F:
		L = M
	else:
		R = min(R - 1, M)
print(L)


import math
inf = math.inf
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))

def solve(m):
	cs = [0]
	mn = inf
	for a in arr:
		if a < m:
			cs.append(cs[-1] - 1)
		else:
			cs.append(cs[-1] + 1)
	for r in range(k, n + 1):
		mn = min(mn, cs[r - k])
		if cs[r] - mn > 0:
			return True
	return False
low = 0
hi = n + 1
while low + 1 < hi:
	middle = (low + hi) // 2
	if solve(middle):
		low = middle
	else:
		hi = middle
print(low)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
lo = 1
hi = n
ans = 1
z = 0
while lo <= hi:
	m = (lo + hi) // 2
	l2 = []
	l1 = [0] * n
	for i in range(n):
		if l[i] < m:
			l2.append(-1)
		else:
			l2.append(1)
	for i in range(1, n):
		l2[i] += l2[i - 1]
	c = -n
	for i in range(n - 1, -1, -1):
		c = max(c, l2[i])
		l1[i] = c
	c = n
	f = 0
	if l1[k - 1] > 0:
		f = 1
	c = l2[0]
	for i in range(1, n - k + 1):
		a = l1[i + k - 1]
		if a - c > 0:
			f = 1
			break
		c = min(c, l2[i])
	if f:
		ans = m
		lo = m + 1
	else:
		hi = m
	if lo == hi:
		if z:
			break
		z += 1
print(ans)


def find(x):
	pre = [0] * (n + 1)
	cur = 0
	for i in range(n):
		if a[i] < x:
			cur -= 1
		else:
			cur += 1
		if i >= k - 1:
			if cur - pre[i - k] > 0:
				return 1
		pre[i] = min(pre[i - 1], cur)
	return 0
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = 1
r = n
while l <= r:
	m = (l + r) // 2
	if find(m):
		l = m + 1
	else:
		r = m - 1
print(r)


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	from collections import deque

	def slide_min(A, k):
		D = deque()
		ret = []
		for i in range(k):
			a = A[i]
			while True:
				if D:
					if a <= A[D[-1]]:
						D.pop()
					else:
						D.append(i)
						break
				else:
					D.append(i)
					break
		ret.append(A[D[0]])
		for i in range(1, len(A) - k + 1):
			if D[0] == i - 1:
				D.popleft()
			j = i + k - 1
			a = A[j]
			while True:
				if D:
					if a <= A[D[-1]]:
						D.pop()
					else:
						D.append(j)
						break
				else:
					D.append(j)
					break
			ret.append(A[D[0]])
		return ret
	(N, K) = map(int, input().split())
	A = list(map(int, input().split()))
	ok = min(A)
	ng = max(A) + 1
	mid = (ok + ng) // 2
	while ng - ok > 1:
		AA = [0]
		for a in A:
			if a >= mid:
				AA.append(AA[-1] - 1)
			else:
				AA.append(AA[-1] + 1)
		AA.extend([N + 3] * (N - K + 3))
		S = slide_min(AA, N - K + 1)
		mi = N + 3
		for i in range(N - K + 1):
			mi = min(mi, S[i + K] - AA[i])
		if mi <= -1:
			ok = mid
		else:
			ng = mid
		mid = (ok + ng) // 2
	print(ok)
main()


def solve(N, K, A):
	L = 1
	R = N + 1
	while L < R - 1:
		cur_guess = int((L + R) / 2)
		smaller_until_end = [0]
		smaller_before_start = [0]
		for a in A:
			if a < cur_guess:
				smaller_until_end.append(smaller_until_end[-1] + 1)
			else:
				smaller_until_end.append(smaller_until_end[-1] - 1)
			smaller_before_start.append(max(smaller_before_start[-1], smaller_until_end[-1]))
		legalabb = False
		for i in range(N - K + 1):
			if smaller_until_end[i + K] < smaller_before_start[i]:
				legalabb = True
		if legalabb:
			L = cur_guess
		else:
			R = cur_guess
	return L

def run():
	out = ''
	(N, K) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	print(solve(N, K, A))
run()


a = []
(n, k) = (0, 0)

def check(median):
	mini = 2 * 10 ** 5 + 1
	part_sums = [0]
	for val in a[:k]:
		part_sums.append(part_sums[-1] + (val >= median) - (val < median))
	for (key, val) in enumerate(a[k:]):
		mini = min(mini, part_sums[key])
		if part_sums[-1] - mini > 0:
			return True
		part_sums.append(part_sums[-1] + (val >= median) - (val < median))
	mini = min(mini, part_sums[n - k])
	if part_sums[-1] - mini > 0:
		return True
	return False

def search(l, r) -> int:
	if l == r - 1:
		return l
	mid = (l + r) // 2
	if check(mid):
		return search(mid, r)
	return search(l, mid)
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
print(search(1, 2 * 10 ** 5 + 1))


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
lo = 1
hi = n
ans = 1
z = 0
while lo <= hi:
	m = (lo + hi) // 2
	l2 = []
	l1 = [0] * n
	for i in range(n):
		if l[i] < m:
			l2.append(-1)
		else:
			l2.append(1)
	for i in range(1, n):
		l2[i] += l2[i - 1]
	c = -n
	for i in range(n - 1, -1, -1):
		c = max(c, l2[i])
		l1[i] = c
	c = n
	f = 0
	if l1[k - 1] > 0:
		f = 1
	c = l2[0]
	for i in range(1, n - k + 1):
		a = l1[i + k - 1]
		if a - c > 0:
			f = 1
			break
		c = min(c, l2[i])
	if f:
		ans = m
		lo = m + 1
	else:
		hi = m
	if lo == hi:
		if z:
			break
		z += 1
print(ans)


from bisect import bisect, bisect_left
from heapq import heapify, heappop, heappush
from itertools import accumulate, islice, chain
from sys import stdin, gettrace
if gettrace():

	def inputi():
		return input()
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def main():
	(n, k) = map(int, input().split())
	aa = [int(a) for a in input().split()]
	l = 1
	r = n + 1
	while l + 1 < r:
		m = (l + r) // 2
		bb = list(accumulate((1 if a >= m else -1 for a in aa)))
		mn = list(accumulate([0] + bb[:-k], min))
		if any((b - m1 > 0 for (b, m1) in zip(bb[k - 1:], mn))):
			l = m
		else:
			r = m
	print(l)
main()


import sys
input = sys.stdin.readline
(N, K) = map(int, input().split())
a = list(map(int, input().split()))

def check(x):
	t = [0] * N
	for i in range(N):
		if a[i] < x:
			t[i] = -1
		else:
			t[i] = 1
	cs = [0] * (N + 1)
	for i in range(N):
		cs[i + 1] = cs[i] + t[i]
	csmx = [0] * (N + 1)
	csmx[-1] = cs[-1]
	for i in range(N, 0, -1):
		csmx[i - 1] = max(csmx[i], cs[i - 1])
	for i in range(N - K + 1):
		d = csmx[i + K] - cs[i]
		if d > 0:
			return True
	return False
ok = 0
ng = N + 1
while ng - ok > 1:
	m = (ok + ng) // 2
	if check(m):
		ok = m
	else:
		ng = m
print(ok)


import io
import os
from collections import Counter, defaultdict, deque
inf = float('inf')

class RangeQuery:

	def __init__(self, data, func=min):
		self.func = func
		self._data = _data = [list(data)]
		(i, n) = (1, len(_data[0]))
		while 2 * i <= n:
			prev = _data[-1]
			_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
			i <<= 1

	def query(self, start, stop):
		depth = (stop - start).bit_length() - 1
		return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

	def __getitem__(self, idx):
		return self._data[0][idx]

def solve1(N, K, A):
	best = (-inf,)
	for i in range(N):
		for j in range(i + K, N + 1):
			k = j - i
			m = (k - 1) // 2
			median = sorted(A[i:j])[m]
			best = max(best, (median, k))
	return best[0]

def solve(N, K, A):

	def check(median):
		pref = [0]
		for x in A:
			if x < median:
				pref.append(pref[-1] + 0)
			else:
				pref.append(pref[-1] + 1)
		temp = []
		for (i, x) in enumerate(pref):
			temp.append(2 * x - i)
		rmq = RangeQuery(temp)
		for j in range(K, N + 1):
			if False:
				mn = inf
				for i in range(j - K + 1):
					assert j - i >= K
					mn = min(mn, 2 * pref[i] - i)
				assert mn == rmq.query(0, j - K + 1)
			else:
				mn = rmq.query(0, j - K + 1)
			if 2 * pref[j] - j > mn:
				return True
		return False
	lo = 0
	hi = max(A)
	best = -inf
	while lo <= hi:
		mid = (lo + hi) // 2
		if check(mid):
			lo = mid + 1
			best = max(best, mid)
		else:
			hi = mid - 1
	return best
DEBUG = False
if DEBUG:
	import random
	random.seed(0)
	for _ in range(10000):
		N = random.randint(1, 10)
		K = random.randint(1, N)
		A = [random.randint(1, 10) for i in range(N)]
		ans1 = solve1(N, K, A)
		ans = solve(N, K, A)
		print('tc', _, N, K, A, ans1, ans)
		assert ans1 == ans
		print(ans1)
	exit()
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = 1
for tc in range(1, TC + 1):
	(N, K) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	ans = solve(N, K, A)
	print(ans)


import os
import sys
from io import BytesIO, IOBase
_print = print
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def inp():
	return sys.stdin.readline().rstrip()

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())
from itertools import accumulate

def solve():
	(n, k) = mpint()
	arr = tuple(mpint())

	def check(x):
		b = [-1 if a < x else 1 for a in arr]
		prefix = tuple(accumulate(b))
		if prefix[k - 1] > 0:
			return True
		min_prefix = tuple(accumulate(prefix, min))
		for j in range(k, n):
			if prefix[j] - min(0, min_prefix[j - k]) > 0:
				return True
		return False
	(lo, hi) = (0, n)
	while lo < hi:
		mi = lo + hi >> 1
		if not check(mi + 1):
			hi = mi
		else:
			lo = mi + 1
	return lo

def main():
	print(solve())
DEBUG = 0
URL = 'https://codeforces.com/contest/1486/problem/D'
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


(n, k) = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = a[:]
b.sort()

def Check(val):
	mn = [0]
	tmp = 0
	for i in range(n):
		tmp += 1 if a[i] >= val else -1
		mn.append(min(mn[i], tmp))
		if i >= k - 1 and tmp > mn[i - k + 1]:
			return True
	return False
l = 0
r = n - 1
while l < r:
	mid = (l + r + 1) // 2
	if Check(b[mid]):
		l = mid
	else:
		r = mid - 1
print(b[l])


def check(A, x, k):
	n = len(A)
	C = [0]
	for i in range(len(A)):
		if A[i] >= x:
			C.append(C[-1] + 1)
		else:
			C.append(C[-1] - 1)
	mn = C[0]
	for i in range(k, n + 1):
		mn = min(mn, C[i - k])
		if C[i] - mn > 0:
			return True
	return False
(n, k) = map(int, input().split())
begin = 1
A = list(map(int, input().split()))
end = max(A)
while end - begin >= 2:
	middle = (end + begin) // 2
	if check(A, middle, k):
		begin = middle
	else:
		end = middle
if check(A, end, k):
	print(end)
else:
	print(begin)


def check(x):
	for i in range(n):
		a[i] = arr[i]
	for i in range(n):
		if a[i] >= x:
			a[i] = 1
		else:
			a[i] = -1
	sum_a[0] = a[0]
	for i in range(1, n):
		sum_a[i] = sum_a[i - 1] + a[i]
	min_a[0] = min(0, sum_a[0])
	for i in range(1, n):
		min_a[i] = min(min_a[i - 1], sum_a[i])
	for i in range(k - 1, n):
		if i == k - 1:
			if sum_a[i] > 0:
				return 1
		elif sum_a[i] - min_a[i - k] > 0:
			return 1
	return 0
(n, k) = map(int, input().split())
arr = list(map(int, input().split()))
sum_a = [0] * n
min_a = [0] * n
a = [0] * n
s = 1
e = n
ans = -1
while s <= e:
	mid = (s + e) // 2
	if check(mid):
		ans = mid
		s = mid + 1
	else:
		e = mid - 1
print(ans)


import sys
import math
from collections import Counter
is_debug = 0
readln = sys.stdin.readline

def write(obj):
	sys.stdout.write(str(obj))

def readint():
	return int(readln().strip())

def readints():
	return map(int, readln().split())

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

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

def write(obj):
	sys.stdout.write(str(obj))

def dbg(*args):
	if is_debug:
		print(' '.join(map(str, args)))

def check(A, mid, k):
	presum = []
	for a in A:
		a = 1 if a >= mid else -1
		x = a + (presum[-1] if presum else 0)
		presum.append(x)
	dbg(mid, presum)

	def RangeSum(i1, i2):
		return presum[i2] - (presum[i1 - 1] if i1 > 0 else 0)
	if RangeSum(0, k - 1) > 0:
		return True
	si = 0
	for ei in range(k, len(A)):
		if RangeSum(si, ei - k) <= 0:
			si = ei - k + 1
		if RangeSum(si, ei) > 0:
			return True
	return False

def solve():
	(n, k) = readints()
	A = list(readints())
	(l, r) = (1, n)
	ans = 0
	while l <= r:
		mid = (l + r) // 2
		if check(A, mid, k):
			ans = mid
			l = mid + 1
		else:
			r = mid - 1
	return ans
t = 1
for _ in range(t):
	ret = solve()
	if type(ret) in [int, str]:
		write(ret)
	else:
		write('\n'.join(ret))
	write('\n')


(n, m) = (int(num) for num in input().split())
numlist = [int(num) for num in input().split()]
r = n + 1
l = 0
while r - l > 1:
	mid = (r + l) // 2
	comlist = [0]
	for i in numlist:
		if i < mid:
			comlist.append(comlist[-1] - 1)
		else:
			comlist.append(comlist[-1] + 1)
	minn = 10 ** 10
	jg = 0
	for i in range(m, n + 1):
		minn = min(minn, comlist[i - m])
		if comlist[i] - minn > 0:
			jg = 1
			l = mid
			break
	if jg == 0:
		r = mid
print(l)


import sys
input = sys.stdin.readline
from collections import defaultdict
(n, k) = map(int, input().split())
v = list(map(int, input().split()))

def func(i, j):
	if i >= j:
		return 1
	return -1

def check(x):
	temp = [func(v[i], x) for i in range(n)]
	pref = [temp[0] for i in range(n)]
	pref_min = [temp[0] for i in range(n)]
	for i in range(1, n):
		pref[i] = pref[i - 1] + temp[i]
		pref_min[i] = min(pref[i], pref_min[i - 1])
	for i in range(k - 1, n):
		if i == k - 1:
			if pref[i] > 0:
				return True
		elif pref[i] - pref_min[i - k] > 0 or pref[i] > 0:
			return True
	return False
(l, h, maxx) = (1, n, 1)
while l + 1 < h:
	mid = (l + h) // 2
	if check(mid):
		l = mid
	else:
		h = mid - 1
if check(l + 1):
	print(l + 1)
else:
	print(l)


def checkPossibleMedia(med, a, n, k):
	cntsDeltaArr = [None for _ in range(n)]
	cntsDelta = 0
	for (i, x) in enumerate(a):
		if x >= med:
			cntsDelta += 1
		elif x < med:
			cntsDelta -= 1
		cntsDeltaArr[i] = cntsDelta
	oddIdxMins = [inf for _ in range(n)]
	evenIdxMins = [inf for _ in range(n)]
	oddIdxMins[0] = 0
	for i in range(n):
		if i % 2 == 0:
			evenIdxMins[i] = min(evenIdxMins[i], cntsDeltaArr[i])
		else:
			oddIdxMins[i] = min(oddIdxMins[i], cntsDeltaArr[i])
		if i - 1 >= 0:
			evenIdxMins[i] = min(evenIdxMins[i], evenIdxMins[i - 1])
			oddIdxMins[i] = min(oddIdxMins[i], oddIdxMins[i - 1])
	res = -1
	for r in range(k - 1, n):
		l = r - k + 1
		if l == 0:
			if k % 2 == 0:
				if cntsDeltaArr[r] >= 2:
					res = 1
			elif cntsDeltaArr[r] >= 1:
				res = 1
		elif r % 2 == 0:
			if cntsDeltaArr[r] - evenIdxMins[l - 1] >= 2:
				res = 1
			if cntsDeltaArr[r] - oddIdxMins[l - 1] >= 1:
				res = 1
		else:
			if cntsDeltaArr[r] - evenIdxMins[l - 1] >= 1:
				res = 1
			if cntsDeltaArr[r] - oddIdxMins[l - 1] >= 2:
				res = 1
		if res == 1:
			break
	return res

def main():
	(n, k) = readIntArr()
	a = readIntArr()
	med = 0
	b = n
	while b > 0:
		while med + b <= n and checkPossibleMedia(med + b, a, n, k) == 1:
			med += b
		b //= 2
	ans = med
	print(ans)
	return
import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]
inf = float('inf')
MOD = 10 ** 9 + 7
main()


(n, k) = map(int, input().split())
A = list(map(int, input().split()))
from itertools import accumulate

def is_ok(x):
	cnt = 0
	B = [-1] * n
	for (i, a) in enumerate(A):
		if a >= x:
			B[i] = 1
	C = [0] + B
	C = list(accumulate(C))
	if C[k] > 0:
		return True
	minl = C[0]
	for i in range(k + 1, n + 1):
		minl = min(minl, C[i - k])
		if C[i] - minl > 0:
			return True
	else:
		return False
ok = 0
ng = n + 1
while ok + 1 < ng:
	c = (ng + ok) // 2
	if is_ok(c):
		ok = c
	else:
		ng = c
print(ok)


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

def ok(m):
	cs = [0]
	mn = float('inf')
	for a in aa:
		cs.append(cs[-1] - 1 if a < m else cs[-1] + 1)
	for r in range(k, n + 1):
		mn = min(mn, cs[r - k])
		if cs[r] - mn > 0:
			return True
	return False
(l, r) = (0, n + 1)
while l + 1 < r:
	m = (l + r) // 2
	if ok(m):
		l = m
	else:
		r = m
print(l)


import sys, functools, collections, bisect, math
input = sys.stdin.readline
(n, k) = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))
l = 0
h = n + 1
while l < h:
	mid = (l + h) // 2
	res = [0]
	for i in arr:
		if i < mid:
			res.append(res[-1] - 1)
		else:
			res.append(res[-1] + 1)
	mi = 0
	for i in range(n - k + 1):
		mi = min(mi, res[i])
		if res[i + k] - mi > 0:
			l = mid + 1
			break
	else:
		h = mid
print(l - 1)


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
v = 1
r = n + 1
ans = 0
while r - v > 1:
	d = [0]
	mid = (v + r) // 2
	m = 100001
	for i in range(1, n + 1):
		if l[i - 1] >= mid:
			d.append(1)
		else:
			d.append(-1)
		d[i] += d[i - 1]
	found = 0
	for i in range(k, n + 1):
		m = d[i - k] if d[i - k] < m else m
		if d[i] - m > 0:
			found = 1
			break
	if found == 1:
		v = mid
	else:
		r = mid
print(v)


def check_lower_bound(n, k, a, candidate_min):
	converted_a = [1 if a_i >= candidate_min else -1 for a_i in a]
	prefix_sums = [0]
	for converted_a_i in converted_a:
		prefix_sums.append(prefix_sums[-1] + converted_a_i)
	prefix_min = 0
	for r in range(k, n + 1):
		if prefix_sums[r] - prefix_min > 0:
			return True
		prefix_min = min(prefix_min, prefix_sums[r - k + 1])
	return False
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
low = 0
high = max(a)
while low < high:
	mid = (low + high) // 2
	if low + 1 == high:
		if check_lower_bound(n, k, a, high):
			low = high
		else:
			high = low
	elif check_lower_bound(n, k, a, mid):
		low = mid
	else:
		high = mid - 1
print(low)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil, sqrt, log2
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def testcase(t):
	for pp in range(t):
		solve(pp)

def google(p):
	print('Case #' + str(p) + ': ', end='')

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

def power(x, y, p):
	y %= p - 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

class FenwickTree:

	def __init__(self, x):
		self.bit = x
		for i in range(len(x)):
			j = i | i + 1
			if j < len(x):
				x[j] += x[i]

	def update(self, idx, x):
		while idx < len(self.bit):
			self.bit[idx] += x
			idx |= idx + 1

	def query(self, end):
		x = 0
		while end:
			x += self.bit[end - 1]
			end &= end - 1
		return x

	def findkth(self, k):
		idx = -1
		for d in reversed(range(len(self.bit).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(self.bit) and k >= self.bit[right_idx]:
				idx = right_idx
				k -= self.bit[idx]
		return idx + 1

	def printpref(self):
		out = []
		for i in range(1, len(self.bit) + 1):
			out.append(self.query(i))
		print(out)

class RangeQuery:

	def __init__(self, data, func=max):
		self.func = func
		self._data = _data = [list(data)]
		(i, n) = (1, len(_data[0]))
		while 2 * i <= n:
			prev = _data[-1]
			_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
			i <<= 1

	def query(self, start, stop):
		depth = (stop - start).bit_length() - 1
		return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])

	def __getitem__(self, idx):
		return self._data[0][idx]

class SegmentTree:

	def __init__(self, data, default=inf, func=max):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		start += self._size
		stop += self._size
		res_left = res_right = self._default
		while start < stop:
			if start & 1:
				res_left = self._func(res_left, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res_right = self._func(self.data[stop], res_right)
			start >>= 1
			stop >>= 1
		return self._func(res_left, res_right)

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

def chck(mid, a, k):
	b = []
	for i in range(len(a)):
		if a[i] >= mid:
			b.append(1)
		else:
			b.append(-1)
	pre = [0] * (len(a) + 1)
	for i in range(len(b)):
		pre[i] = pre[i - 1] + b[i]
	mx = [-inf] * (len(b) + 1)
	for i in range(len(b) - 1, -1, -1):
		mx[i] = max(mx[i + 1], pre[i])
	f = False
	for i in range(len(b)):
		if i + k > len(b):
			break
		if b[i] == 1:
			if mx[i + k - 1] >= pre[i]:
				f = True
				break
		elif mx[i + k - 1] > pre[i] + 1:
			f = True
			break
	if f:
		return True
	return False

def solve(case):
	(n, k) = sep()
	a = lis()
	lo = 1
	hi = 2 * 10 ** 5 + 10
	ans = lo
	while lo <= hi:
		mid = (lo + hi) // 2
		if chck(mid, a, k):
			ans = mid
			lo = mid + 1
		else:
			hi = mid - 1
	print(ans)
testcase(1)


import sys, math, itertools, random, bisect
from collections import defaultdict
INF = sys.maxsize

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()
mod = 10 ** 9 + 7

def check(a, m, k):
	b = [1 if i >= m else -1 for i in a]
	for i in range(1, len(b)):
		b[i] += b[i - 1]
	ans = False
	if b[k - 1] > 0:
		ans = True
	mn = 0
	for i in range(k, len(b)):
		mn = min(mn, b[i - k])
		if b[i] - mn > 0:
			ans = True
	return ans
for _ in range(1):
	(n, k) = get_ints()
	a = get_array()
	(l, r) = (1, n)
	while l <= r:
		m = (l + r) // 2
		if check(a, m, k):
			l = m + 1
		else:
			r = m - 1
	print(r)


import sys
import math
import heapq
import bisect
from collections import Counter
from collections import defaultdict
from io import BytesIO, IOBase
import string

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None
		self.BUFSIZE = 8192

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def get_int():
	return int(input())

def get_ints():
	return list(map(int, input().split(' ')))

def get_int_grid(n):
	return [get_ints() for _ in range(n)]

def get_str():
	return input().split(' ')

def yes_no(b):
	if b:
		return 'YES'
	else:
		return 'NO'

def binary_search(good, left, right, delta=1, right_true=False):
	limits = [left, right]
	while limits[1] - limits[0] > delta:
		if delta == 1:
			mid = sum(limits) // 2
		else:
			mid = sum(limits) / 2
		if good(mid):
			limits[int(right_true)] = mid
		else:
			limits[int(~right_true)] = mid
	if good(limits[int(right_true)]):
		return limits[int(right_true)]
	else:
		return False

def prefix_sums(a, drop_identity=False):
	p = [0]
	for x in a:
		p.append(p[-1] + x)
	if drop_identity:
		return p[1:]
	else:
		return p

def prefix_mins(a, drop_identity=False):
	p = [float('inf')]
	for x in a:
		p.append(min(p[-1], x))
	if drop_identity:
		return p[1:]
	else:
		return p

def solve_a():
	n = get_int()
	h = get_ints()
	p = prefix_sums(h)
	for i in range(1, n + 1):
		if p[i] < i * (i - 1) // 2:
			return False
	return True

def solve_b():
	n = get_int()
	points_x = []
	points_y = []
	for point in range(n):
		(x, y) = get_ints()
		points_x.append(x)
		points_y.append(y)
	points_x.sort()
	points_y.sort()
	if n % 2 == 1:
		return 1
	else:
		return (1 + points_x[n // 2] - points_x[n // 2 - 1]) * (1 + points_y[n // 2] - points_y[n // 2 - 1])

def solve_c():
	n = get_int()
	responses = {}

	def query(l, r):
		if (l, r) not in responses:
			print('?', l, r)
			sys.stdout.flush()
			responses[l, r] = get_int()
		return responses[l, r]

	def guess(x):
		print('!', x)
		sys.stdout.flush()
	smax = query(1, n)
	if smax != 1 and query(1, smax) == smax:
		l = 1
		r = smax
		while r - l > 1:
			m = (l + r) // 2
			if query(m, smax) == query(1, smax):
				l = m
			else:
				r = m
		guess(l)
	elif smax != n:
		l = smax
		r = n
		while r - l > 1:
			m = (l + r) // 2
			if query(smax, m) == query(smax, n):
				r = m
			else:
				l = m
		guess(r)

def solve_d():
	(n, k) = get_ints()
	a = get_ints()

	def good(x):
		b = [(-1) ** int(elem < x) for elem in a]
		pref_sums = prefix_sums(b)
		pref_sums_mins = prefix_mins(pref_sums, drop_identity=True)
		for i in range(k, n + 1):
			if pref_sums[i] > pref_sums_mins[i - k]:
				return True
		return False
	return binary_search(good, 0, n + 1)
print(solve_d())


from sys import stdin, stdout

def max_median(n, k, a_a):
	l = 1
	h = 2 * 10 ** 5
	while l < h:
		pre_sum = [0] * (n + 1)
		min_sum = [0] * (n + 1)
		found = False
		m = (l + h + 1) // 2
		for i in range(n):
			v = 1 if a_a[i] >= m else -1
			pre_sum[i + 1] = v + pre_sum[i]
			min_sum[i + 1] = min(min_sum[i], pre_sum[i + 1])
			if i + 1 - k >= 0 and pre_sum[i + 1] - min_sum[i + 1 - k] > 0:
				found = True
				l = m
				break
		if not found:
			h = m - 1
	return l
(n, k) = map(int, stdin.readline().split())
a_a = list(map(int, stdin.readline().split()))
r = max_median(n, k, a_a)
stdout.write(str(r) + '\n')


import random

def good(n, k, a, m):
	b = [[-1, 1][e >= m] for e in a]
	pref_sum = [0]
	for i in range(n):
		pref_sum.append(pref_sum[-1] + b[i])
	pref_min = [0]
	for i in range(n):
		pref_min.append(min(pref_min[-1], pref_sum[i + 1]))
	s = 0
	for i in range(n):
		s += b[i]
		if i - k + 1 >= 0:
			if s - pref_min[i - k + 1] > 0:
				return True
	return False

def solve(n, k, a):
	low = 1
	high = max(a) + 1
	while low + 1 < high:
		mid = (low + high) // 2
		if good(n, k, a, mid):
			low = mid
		else:
			high = mid
	return low

def median(a):
	return sorted(a)[(len(a) - 1) // 2]

def brute(n, k, a):
	return max((median(a[i:j]) for i in range(n) for j in range(i + k, n + 1)))

def debug():
	n = 20
	for _ in range(1000):
		k = random.randint(1, n)
		a = [random.randint(1, 50) for _ in range(n)]
		expected = brute(n, k, a)
		actual = solve(n, k, a)
		if expected != actual:
			print(f'ERROR: {expected} != {actual}')
			print(n, k, a)
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
print(solve(n, k, a))


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
from bisect import *
tc = 1
for _ in range(tc):
	(n, k) = inp()
	a = inp()

	def possible(a, mid, k):
		temp = [0] * (len(a) + 1)
		for i in range(len(a)):
			temp[i + 1] = temp[i] + (a[i] >= mid) - (a[i] < mid)
		Min = 0
		for i in range(k, n + 1):
			Min = min(Min, temp[i - k])
			if temp[i] - Min > 0:
				return True
		return False
	(low, high) = (1, n)
	while low <= high:
		mid = (low + high) // 2
		if possible(a, mid, k):
			ans = mid
			low = mid + 1
		else:
			high = mid - 1
	print(ans)


import sys
input = sys.stdin.readline
flush = sys.stdout.flush
from itertools import accumulate
(n, k) = map(int, input().split())
A = list(map(int, input().split()))
(left, right) = (min(A), max(A))
while left < right:
	mid = right - (right - left) // 2
	B = [1 if a >= mid else -1 for a in A]
	acc = [0] + list(accumulate(B))
	minv = [0] * (n + 1)
	for i in range(1, n + 1):
		minv[i] = min(minv[i - 1], acc[i])
	flag = 0
	for i in range(k, n + 1):
		if acc[i] > minv[i - k]:
			flag = 1
			break
	if flag:
		left = mid
	else:
		right = mid - 1
print(left)


def check(v, n, k, mid):
	tmp = []
	for i in v:
		if i < mid:
			tmp.append(-1)
		else:
			tmp.append(1)
	for i in range(1, len(v)):
		tmp[i] += tmp[i - 1]
	maxArr = [0] * n
	maxArr[n - 1] = tmp[n - 1]
	maxArr[n - 2] = tmp[n - 2]
	for i in range(n - 3, -1, -1):
		maxArr[i] = max(maxArr[i + 2], tmp[i])
	for i in range(0, n - k + 1):
		leftval = 0
		rightval = maxArr[i + k - 1]
		if i - 1 >= 0:
			leftval = tmp[i - 1]
		if k % 2 == 0:
			if rightval - leftval >= 2:
				return True
		elif rightval - leftval >= 1:
			return True
		if i + k < n:
			rightval = maxArr[i + k]
			if (k + 1) % 2 == 0:
				if rightval - leftval >= 2:
					return True
			elif rightval - leftval >= 1:
				return True
	return False

def main():
	(n, k) = map(int, input().split())
	v = list(map(int, input().split()))
	if n == 2:
		if k == 1:
			maxele = max(v[0], v[1])
			print(f'{maxele}')
		else:
			minele = min(v[0], v[1])
			print(f'{minele}')
		return
	(low, high) = (1, 100000000000000.0)
	ans = low
	while low <= high:
		mid = int((low + high) / 2)
		if check(v, n, k, mid):
			ans = mid
			low = mid + 1
		else:
			high = mid - 1
	print(f'{ans}')
	return
main()


import sys
import math
import collections
import bisect
import itertools
import decimal
import heapq
INF = 10 ** 20
MOD = 10 ** 9 + 7

def ni():
	return int(sys.stdin.buffer.readline())

def ns():
	return map(int, sys.stdin.buffer.readline().split())

def na():
	return list(map(int, sys.stdin.buffer.readline().split()))

def na1():
	return list(map(lambda x: int(x) - 1, sys.stdin.buffer.readline().split()))

def flush():
	return sys.stdout.flush()

def nic():
	return int(sys.stdin.readline())

def nsc():
	return map(int, sys.stdin.readline().split())

def nac():
	return list(map(int, sys.stdin.readline().split()))

def na1c():
	return list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))

def main():
	(n, k) = ns()
	a = na()
	ok = 1
	ng = n + 1
	while ng - ok > 1:
		nxt = (ok + ng) // 2
		cnt = [1 if a[i] >= nxt else -1 for i in range(n)]
		cnt = [0] + list(itertools.accumulate(cnt))
		premn = 0
		for i in range(k, len(cnt)):
			premn = min(premn, cnt[i - k])
			if cnt[i] - premn > 0:
				ok = nxt
				break
		if ok != nxt:
			ng = nxt
	print(ok)
main()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
import time
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			self.os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def getMat(n):
	return [getInts() for _ in range(n)]

def isInt(s):
	return '0' <= s[0] <= '9'
MOD = 10 ** 9 + 7

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def solve():
	(N, K) = getInts()
	A = getInts()

	def works(X):
		prefs = [0]
		curr = 0
		for a in A:
			if a >= X:
				curr += 1
			else:
				curr -= 1
			prefs.append(curr)
		min_prefs = [0]
		min_ = 0
		for i in range(1, len(prefs)):
			min_ = min(min_, prefs[i])
			min_prefs.append(min_)
		for i in range(K, N + 1):
			if prefs[i] > min_prefs[i - K]:
				return True
		return False
	(L, R) = (0, N + 1)
	while R - L > 1:
		M = (R + L) // 2
		if works(M):
			L = M
		else:
			R = M
	return L
print(solve())


import sys
input = lambda : sys.stdin.readline().rstrip()
(N, K) = map(int, input().split())
A = [int(a) for a in input().split()]
(l, r) = (0, N + 1)
while r - l > 1:
	m = l + r >> 1
	B = [1 if a >= m else -1 for a in A]
	S = [0]
	s = 0
	for b in B:
		s += b
		S.append(s)
	mi = 0
	for i in range(K, N + 1):
		mi = min(mi, S[i - K])
		if S[i] > mi:
			f = 1
			break
	else:
		f = 0
	if f:
		l = m
	else:
		r = m
print(l)


import sys
(n, k) = map(int, sys.stdin.readline().split())
a = list(map(int, sys.stdin.readline().split()))
lena = len(a)

def check(t):
	tmp = [1 if aa >= t else -1 for aa in a]
	p = [0] * lena
	p[0] = tmp[0]
	for i in range(1, lena):
		p[i] = tmp[i] + p[i - 1]
	pm = [0] * lena
	for i in range(1, lena):
		pm[i] = min(p[i - 1], pm[i - 1])
	for i in range(k - 1, lena):
		if p[i] - pm[i - k + 1] > 0:
			return True
	return False
l = 1
r = 2 * 10 ** 5 + 1
while r - l > 1:
	m = (l + r) // 2
	if check(m):
		l = m
	else:
		r = m
print(l)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree1:

	def __init__(self, data, default=10 ** 6, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
MOD = 10 ** 9 + 7

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(200001)]
pp = [0] * 200001

def SieveOfEratosthenes(n=200000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
l = 1
r = n + 1
while r - l > 1:
	mid = (r + l) // 2
	b = [1 if i >= mid else -1 for i in a]
	for i in range(1, len(b)):
		b[i] += b[i - 1]
	ans = False
	if b[k - 1] > 0:
		ans = True
	mn = 0
	for i in range(k, len(b)):
		mn = min(mn, b[i - k])
		if b[i] - mn > 0:
			ans = True
	if ans:
		l = mid
	else:
		r = mid
print(l)


import sys, getpass
import math, random
import functools, itertools, collections, heapq, bisect
from collections import Counter, defaultdict, deque
input = sys.stdin.readline
M9 = 10 ** 9 + 7
MAXINT = sys.maxsize
OFFLINE_TEST = getpass.getuser() == 'hkmac'

def log(*args):
	if OFFLINE_TEST:
		print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)

def solve(*args):
	if OFFLINE_TEST:
		log('----- solving ------')
		log(*args)
		log('----- ------- ------')
	return solve_(*args)

def read_matrix(rows):
	return [list(map(int, input().split())) for _ in range(rows)]

def read_strings(rows):
	return [input().strip() for _ in range(rows)]

def medianSlidingWindow(nums, k):
	(small, large) = ([], [])
	for (i, x) in enumerate(nums[:k]):
		heapq.heappush(small, (-x, i))
	for _ in range(k - (k >> 1)):
		move(small, large)
	ans = [get_med(small, large, k)]
	for (i, x) in enumerate(nums[k:]):
		if x >= large[0][0]:
			heapq.heappush(large, (x, i + k))
			if nums[i] <= large[0][0]:
				move(large, small)
		else:
			heapq.heappush(small, (-x, i + k))
			if nums[i] >= large[0][0]:
				move(small, large)
		while small and small[0][1] <= i:
			heapq.heappop(small)
		while large and large[0][1] <= i:
			heapq.heappop(large)
		ans.append(get_med(small, large, k))
	return ans

def move(h1, h2):
	(x, i) = heapq.heappop(h1)
	heapq.heappush(h2, (-x, i))

def get_med(h1, h2, k):
	return h2[0][0] if k & 1 else -h1[0][0]

def check(arr, q, mink):
	arr = [x - q for x in arr]
	arr = [1 if x > 0 else -1 if x < 0 else 1 for x in arr]
	cursum_advance = sum(arr[:mink])
	cursum = 0
	minsum = 0
	for (x, y) in zip(arr, arr[mink:]):
		cursum += x
		cursum_advance += y
		minsum = min(cursum, minsum)
		if cursum_advance - minsum > 0:
			return True
	return False

def solve_(lst, k):
	size_k = medianSlidingWindow(lst, k)
	log(size_k)
	if k == len(lst):
		return max(size_k)
	size_k1 = medianSlidingWindow(lst, k + 1)
	log(size_k1)
	if k == len(lst) - 1:
		return max(max(size_k), max(size_k1))
	upper = 2 ** 20
	lower = 0
	for i in range(20):
		mid = (upper + lower) // 2
		res = check(lst, mid, k)
		if not res:
			upper = mid
		else:
			lower = mid
	for i in range(mid + 1, mid - 2, -1):
		res = check(lst, i, k)
		if res:
			return max(max(size_k), max(size_k1), i)
	return max(max(size_k), max(size_k1), i)
for case_num in [0]:
	(n, k) = list(map(int, input().split()))
	lst = list(map(int, input().split()))
	res = solve(lst, k)
	print(res)


def check(x):
	b = [1 if ta >= x else -1 for ta in a]
	for i in range(1, len(a)):
		b[i] += b[i - 1]
	mi = 0
	for i in range(0, len(a)):
		if i - k >= 0:
			mi = min(mi, b[i - k])
		if i >= k - 1 and b[i] - mi > 0:
			return True
	return False
(n, k) = map(int, input().split())
a = [int(i) for i in input().split()]
(l, r) = (1, n + 1)
while l + 1 < r:
	mid = (l + r) // 2
	if check(mid):
		l = mid
	else:
		r = mid
print(l)


def solve():
	(n, k) = [int(t) for t in input().split()]
	a = [int(t) for t in input().split()]

	def step(x, y):
		return 1 if x >= y else -1
	(l, r) = (1, n)
	while l < r:
		x = l + (r - l + 1) // 2
		(cur, pref, best) = (0, 0, 0)
		for i in range(n):
			cur += step(a[i], x)
			if i >= k:
				pref += step(a[i - k], x)
			best = min(best, pref)
			if i >= k - 1 and cur - best > 0:
				l = x
				break
		else:
			r = x - 1
	print(l)
solve()


import sys

def get_median(my_list):
	L = len(my_list)
	idx = int((L - 1) / 2)
	my_list = sorted(my_list)
	return my_list[idx]

def first_guess(N, K, A):
	start = -K / 2
	end = 1 * K / 2
	max_median = min(A)
	while end < N:
		end += K / 2
		if end > N:
			end = N
		start = end - K
		cur_seq = A[int(start):int(end)]
		cur_median = get_median(cur_seq)
		if cur_median > max_median:
			max_median = cur_median
	return max_median

def solve(N, K, A):
	A = [-1] + A + [-1]
	N += 2
	if K % 2 == 0 and K < N:
		K += 1
	max_median = first_guess(N, K, A)
	search = True
	while search:
		big_or_small = []
		for (i, a) in enumerate(A):
			if a <= max_median:
				A[i] = 0
				big_or_small.append(-1)
			else:
				big_or_small.append(1)
		seq_sum = sum(big_or_small)
		left_sum_list = []
		right_sum_list = []
		left_sub_sum = 0
		right_sub_sum = 0
		for i in range(N):
			left_sub_sum += big_or_small[i]
			right_sub_sum += big_or_small[N - i - 1]
			left_sum_list.append(left_sub_sum)
			right_sum_list.append(right_sub_sum)
		len_sum_list = len(left_sum_list)
		for i in range(1, len_sum_list):
			if left_sum_list[i] > left_sum_list[i - 1]:
				left_sum_list[i] = left_sum_list[i - 1]
			if right_sum_list[i] > right_sum_list[i - 1]:
				right_sum_list[i] = right_sum_list[i - 1]
		max_cut_size = N - K
		min_cut_sum = 0
		for i in range(max_cut_size):
			if left_sum_list[i] < 0:
				min_right_sub_sum = right_sum_list[max_cut_size - i - 1]
				if left_sum_list[i] + min_right_sub_sum < min_cut_sum:
					min_cut_sum = left_sum_list[i] + min_right_sub_sum
					best_i = i
		if min_cut_sum < seq_sum:
			aux_seq = right_sum_list[:max_cut_size - best_i]
			len_aux_seq = len(aux_seq)
			argmin_aux_seq = -1
			min_aux_seq = 2
			for i in range(len_aux_seq):
				if aux_seq[i] < min_aux_seq:
					min_aux_seq = aux_seq[i]
					argmin_aux_seq = i
			new_best_sequence = A[best_i + 1:-argmin_aux_seq - 1]
			max_median = get_median(new_best_sequence)
		else:
			search = False
	whole_median = get_median(A)
	if N > 1:
		whole_median1 = get_median(A[:-1])
		whole_median2 = get_median(A[1:])
		if whole_median1 > max_median:
			max_median = whole_median1
		if whole_median2 > max_median:
			max_median = whole_median2
	if whole_median > max_median:
		max_median = whole_median
	return max_median

def run():
	out = ''
	(N, K) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	print(solve(N, K, A))
run()


from bisect import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def A(n):
	return [0] * n

def AI(n, x):
	return [x] * n

def G(n):
	return [[] for i in range(n)]

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class ST:

	def __init__(self, arr):
		n = len(arr)
		mx = n.bit_length()
		self.st = [[0] * mx for i in range(n)]
		for i in range(n):
			self.st[i][0] = arr[i]
		for j in range(1, mx):
			for i in range(n - (1 << j) + 1):
				self.st[i][j] = max(self.st[i][j - 1], self.st[i + (1 << j - 1)][j - 1])

	def query(self, l, r):
		if l > r:
			return -inf
		s = (r + 1 - l).bit_length() - 1
		return max(self.st[l][s], self.st[r - (1 << s) + 1][s])

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return flag

def dij(s, graph):
	d = {}
	d[s] = 0
	heap = [(0, s)]
	seen = set()
	while heap:
		(dis, u) = heappop(heap)
		if u in seen:
			continue
		seen.add(u)
		for (v, w) in graph[u]:
			if v not in d or d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

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

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

def RP(nums):
	n = len(nums)
	s = set(nums)
	d = {}
	for (i, k) in enumerate(sorted(s), 1):
		d[k] = i
	bi = BIT([0] * (len(s) + 1))
	ans = 0
	for i in range(n - 1, -1, -1):
		ans += bi.query(d[nums[i]] - 1)
		bi.update(d[nums[i]], 1)
	return ans

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j, n, m):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	if len(g[r]) == 1 and p != -1:
		yield None
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None

def f(x, a):
	res = [1 if x <= ch else -1 for ch in a]
	pre = [0]
	for ch in res:
		pre.append(pre[-1] + ch)
	stack = [0]
	for i in range(1, n + 1):
		if i >= k:
			if pre[stack[-1]] <= pre[i] - 1:
				l = 0
				r = len(stack) - 1
				while l < r:
					mid = (l + r) // 2
					if pre[stack[mid]] <= pre[i] - 1:
						r = mid
					else:
						l = mid + 1
				if i - stack[l] >= k:
					return True
		if pre[i] < pre[stack[-1]]:
			stack.append(i)
	return False
t = 1
for i in range(t):
	(n, k) = RL()
	a = RLL()
	l = 0
	r = n
	while l < r:
		mid = (l + r + 1) // 2
		if f(mid, a):
			l = mid
		else:
			r = mid - 1
	print(l)