#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define R cin>>
#define ll long long
#define ln cout<<'\n'
#define in(a) insert(a)
#define pb(a) push_back(a)
#define pd(a) printf("%.10f\n",a)
#define mem(a) memset(a,0,sizeof(a))
#define all(c) (c).begin(),(c).end()
#define iter(c) __typeof((c).begin())
#define rrep(i,n) for(ll i=(ll)(n)-1;i>=0;i--)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
#define rep(i,n) REP(i,0,n)
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
ll check(ll n,ll m,ll x,ll y){return x>=0&&x<n&&y>=0&&y<m;}void pr(){ln;}
template<class A,class...B>void pr(const A &a,const B&...b){cout<<a<<(sizeof...(b)?" ":"");pr(b...);}
template<class A>void PR(A a,ll n){rep(i,n)cout<<(i?" ":"")<<a[i];ln;}
const ll MAX=1e9+7,MAXL=1LL<<61,dx[8]={-1,0,1,0,-1,-1,1,1},dy[8]={0,1,0,-1,-1,1,1,-1};
typedef pair<ll,ll> P;

ll d[1111][1111];

void init(ll n,ll m) {
  rep(i,n+1)rep(j,m) d[i][j+1]+=d[i][j];
  rep(j,m+1)rep(i,n) d[i+1][j]+=d[i][j];
}
ll calc(ll x1,ll y1,ll x2,ll y2) {return d[x2][y2]-d[x1][y2]-d[x2][y1]+d[x1][y1];}

void Main() {
  ll n,k;
  cin >> n >> k;
  ll a[n][n];
  rep(i,n)rep(j,n) R a[i][j];
  ll l=-1,r=MAX,e=k*k/2+1;
  while(l+1<r) {
    ll m=(l+r)/2;
    rep(i,n+1)rep(j,n+1) d[i][j]=0;
    rep(i,n) {
      rep(j,n) {
        if(a[i][j]>=m) d[i+1][j+1]++;
      }
    }
    init(n,n);
    ll f=1;
    rep(i,n-k+1) {
      rep(j,n-k+1) {
        ll c=calc(i,j,i+k,j+k);
        if(c<e) f=0; 
      }
    }
    if(!f) r=m;
    else l=m;
  }
  pr(l);
}

int main(){ios::sync_with_stdio(0);cin.tie(0);Main();return 0;}

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define FOR(i,s,n) for(int i = (s); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) for(int i = (n); i >= 0; i--)
#define ALL(n) (n).begin(), (n).end()
#define RALL(n) (n).rbegin(), (n).rend()
#define ATYN(n) cout << ( (n) ? "Yes":"No") << '\n';
#define CFYN(n) cout << ( (n) ? "YES":"NO") << '\n';
#define OUT(n) cout << (n) << '\n';
using ll = long long;
using ull = unsigned long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;

int main(void)
{
    IOS
    int n, m;
    cin >> n >> m;
    vector<ll> h(n), w(m);
    REP(i,n) cin >> h[i];
    REP(i,m) cin >> w[i];
    sort(ALL(h));
    sort(ALL(w));
    vector<ll> h2(n);
    REP(i,n-1) h2[i] = h[i+1] - h[i];
    vector<ll> hsumf(n), hsumb(n);
    for(int i = 0; i < n; i += 2) hsumf[i+2] = hsumf[i] + h2[i];
    for(int i = n-1; i > 0; i -= 2) hsumb[i-2] = hsumb[i] + h2[i-1];
    ll ans = 1e18;
    for(int i = 0; i < n ; i += 2) {
        auto it = lower_bound(ALL(w),h[i]);
        ll hw = abs(*it - h[i]);
        if (it != w.begin()) {
            it--;
            hw = min(hw, abs(h[i]-*it));
        }
        ll tmp = hw + hsumf[i] + hsumb[i];
        ans = min(ans,tmp);
    }

    cout << ans << '\n';

    return 0;
}