#include #include #define INF 1000000000000000LL int cmp_ll (const void *ap, const void *bp) { long long a = *(long long *)ap; long long b = *(long long *)bp; if (a < b) { return -1; } if (a > b) { return 1; } return 0; } int main () { int n = 0; int m = 0; long long d[1500][1500] = {}; int res = 0; long long dp[1500][1501] = {}; long long ans[2] = { -1LL, INF }; res = scanf("%d", &n); res = scanf("%d", &m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { res = scanf("%lld", d[i]+j); } qsort(d[i], m, sizeof(long long), cmp_ll); } while (ans[1]-ans[0] > 1LL) { long long nxt = (ans[0]+ans[1])/2LL; for (int j = 0; j <= m; j++) { dp[0][j] = j; } for (int i = 1; i < n; i++) { int idx1 = 0; int idx2 = 0; for (int j = 0; j < m; j++) { while (idx1 < m && d[i][j]-nxt > d[i-1][idx1]) { idx1++; } while (idx2 < m && d[i][j] >= d[i-1][idx2]) { idx2++; } if (dp[i-1][idx2]-dp[i-1][idx1] > 0) { dp[i][j+1] = dp[i][j]+1; } else { dp[i][j+1] = dp[i][j]; } } } if (dp[n-1][m] > 0) { ans[1] = nxt; } else { ans[0] = nxt; } } if (ans[1] >= INF) { printf("-1\n"); } else { printf("%lld\n", ans[1]); } return 0; }