#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define PI acos(-1)
#define vi vector<int>
const int kMod = 1e9 + 7;
const int kInf = (~(1 << 31)) / 2 - 500;
const ll kInfL = (~(1LL << 63)) / 2 - 2000;

int main() {
  int N, K;
  cin >> N >> K;
  vector<vector<int>> A(N, vector<int>(N));
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      cin >> A[i][j];
    }
  }
  auto check = [&](ll mid) {
    vector<vector<int>> cnt(N + 1, vector<int>(N + 1));
    for (int i = 0; i < N; ++i) {
      for (int j = 0; j < N; ++j) {
        if (A[i][j] <= mid) {
          cnt[i + 1][j + 1] = 1;
        }
      }
    }
    for (int i = 0; i <= N; ++i) {
      for (int j = 1; j <= N; ++j) {
        cnt[i][j] += cnt[i][j - 1];
      }
    }
    for (int i = 0; i <= N; ++i) {
      for (int j = 1; j <= N; ++j) {
        cnt[j][i] += cnt[j - 1][i];
      }
    }
    bool ret = false;
    int mid_idx = (K * K) / 2;
    if (K % 2 == 1) {
      mid_idx = (K * K) / 2 + 1;
    }
    for (int i = K; i <= N; ++i) {
      for (int j = K; j <= N; ++j) {
        ll base = cnt[i][j] + cnt[i - K][j - K];
        base -= cnt[i - K][j] + cnt[i][j - K];
        if (base >= mid_idx) {
          ret = true;
        }
      }
    }
    return ret;
  };
  int left = 0, right = kInf;
  while (right - left > 1) {
    int mid = left + (right - left) / 2;
    if (check(mid)) {
      right = mid;
    } else {
      left = mid;
    }
  }
  if (check(left)) {
    cout << left << endl;
    return 0;
  }
  cout << right << endl;
  return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  long long N, M; cin >> N >> M;
  long long H[N], W[M];
  for (int i = 0; i < N; i++) cin >> H[i];
  for (int i = 0; i < M; i++) cin >> W[i];

  long long dp[(N + 1) / 2][2];
  for (int i = 0; i < (N + 1) / 2; i++) dp[i][0] = dp[i][1] = 0;
  
  sort(H, H + N);
  sort(W, W + M);
  vector<int> Vec;
  for (int i = 0; i < M; i++) Vec.push_back(W[i]);
  sort(Vec.begin(), Vec.end());
  long long now = 0;
  for (long long i = 0; i < (N + 1) / 2; i++){
    if (i == 0){
      dp[0][0] = H[1] - H[0];
      auto itr = lower_bound(Vec.begin(), Vec.end(), H[0]);
      auto itr2 = itr - 1;
      long long min_ = 1000000000000;
      if ((itr - Vec.begin()) < M) min_ = min(min_, *itr - H[0]);
      if ((itr2 - Vec.begin()) >= 0) min_ = min(min_, H[0] - *itr2);
      dp[0][1] = min_;
      continue;
    }
    if (i != (N - 1) / 2) dp[i][0] = dp[i - 1][0] + (H[i * 2 + 1] - H[i * 2]);
    dp[i][1] = dp[i - 1][1] + (H[i * 2] - H[i * 2 - 1]);
    auto itr = lower_bound(Vec.begin(), Vec.end(), H[i * 2]);
    auto itr2 = itr - 1;
    long long min_ = 1000000000000;
    if ((itr - Vec.begin()) < M) min_ = min(min_, *itr - H[i * 2]);
    if ((itr2 - Vec.begin()) >= 0) min_ = min(min_, H[i * 2] - *itr2);
    dp[i][1] = min(dp[i][1], dp[i - 1][0] + min_);
  }
  
  cout << dp[(N - 1) / 2][1] << endl;
}