#include using namespace std; using ll = long long; int main(){ ios::sync_with_stdio(false); cin.tie(0); int h, w; cin >> h >> w; vector> A(h, vector(w)); for(int y = 0; y < h; y++){ for(int x = 0; x < w; x++){ cin >> A[y][x]; } sort(A[y].begin(), A[y].end()); } auto f = [&](int lim){ vector dp(w + 1); dp[0] = 1; for(int y = 0; y + 1 < h; y++){ vector ndp(w + 1); for(int x = 0, l = 0, r = 0; x < w; x++){ dp[x + 1] += dp[x]; if(dp[x] == 0)continue; while(l < w && A[y + 1][l] < A[y][x])l++; while(r < w && A[y + 1][r] <= A[y][x] + lim)r++; ndp[l]++; ndp[r]--; } swap(dp, ndp); } for(int x = 0; x < w; x++){ if(dp[x] >= 1)return true; dp[x + 1] += dp[x]; } return false; }; int ng = -1, ok = 1 << 30, mid; if(!f(ok)){ cout << -1 << '\n'; return 0; } while(ng + 1 < ok){ mid = (ok + ng) / 2; if(f(mid)) ok = mid; else ng = mid; } cout << ok << '\n'; }