#include using namespace std; void fast_io() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { fast_io(); int n, m; cin >> n >> m; vector> d(n, vector(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> d[i][j]; } sort(d[i].begin(), d[i].end()); } { vector dp(n); dp[0] = 0; for (int i = 1; i < n; i++) { dp[i] = lower_bound(d[i].begin(), d[i].end(), d[i - 1][dp[i - 1]]) - d[i].begin(); if (dp[i] == m) { cout << -1 << endl; return 0; } } } int ng = -1, ok = 1e9; while (ok - ng > 1) { int mid = (ok + ng) / 2; vector> dp(n, vector(m)); vector> cum(n, vector(m + 1)); for (int i = 0; i < m; i++) { dp[0][i] = true; cum[0][i + 1] = cum[0][i] + d[0][i]; } for (int i = 1; i < n; i++) { for (int j = 0; j < m; j++) { int lb = lower_bound(d[i - 1].begin(), d[i - 1].end(), d[i][j] - mid) - d[i - 1].begin(); int ub = lower_bound(d[i - 1].begin(), d[i - 1].end(), d[i][j] + 1) - d[i - 1].begin(); if (cum[i - 1][ub] - cum[i - 1][lb] > 0) { dp[i][j] = true; } } for (int j = 0; j < m; j++) { cum[i][j + 1] = cum[i][j] + dp[i][j]; } } bool is_ok = false; for (int i = 0; i < m; i++) { if (dp[n - 1][i]) { is_ok = true; break; } } if (is_ok) { ok = mid; } else { ng = mid; } } cout << ok << endl; }