using
System;
class
GFG{
static
bool
isMaximumMedian(
int
[,] arr,
int
N,
int
K,
int
mid)
{
int
[,]Pre =
new
int
[N + 5, N + 5];
for
(
int
i = 0; i < N; ++i)
{
for
(
int
j = 0; j < N; ++j)
{
Pre[i + 1, j + 1] = Pre[i + 1, j] +
Pre[i, j + 1] -
Pre[i, j];
if
(arr[i, j] <= mid)
Pre[i + 1, j + 1]++;
}
}
int
required = (K * K + 1) / 2;
bool
flag =
false
;
for
(
int
i = K; i <= N; ++i)
{
for
(
int
j = K; j <= N; ++j)
{
int
X = Pre[i, j] - Pre[i - K, j] -
Pre[i, j - K] + Pre[i - K, j - K];
if
(X < required)
flag =
true
;
}
}
return
flag;
}
static
int
maximumMedian(
int
[,] arr,
int
N,
int
K)
{
int
low = 0, high = (
int
)1e9;
while
(low < high)
{
int
mid = low + (high - low) / 2;
if
(isMaximumMedian(arr, N, K, mid))
{
low = mid + 1;
}
else
{
high = mid;
}
}
return
low;
}
public
static
void
Main(
string
[] args)
{
int
[,] arr = { { 1, 5, 12 },
{ 6, 7, 11 },
{ 8, 9, 10 } };
int
N = arr.GetLength(0);
int
K = 2;
Console.WriteLine(maximumMedian(arr, N, K));
}
}