from bisect import bisect_left, bisect_right from itertools import accumulate def find_interval(a: list, lo: int, hi: int) -> tuple[int, int, int]: """ ソート済みリスト a の要素の lo 以上 hi 以下の個数と区間を返す return: 範囲内の個数, l, r """ assert lo <= hi empty = 0, -1, -1 # 区間なし if not a or lo > a[-1] or hi < a[0]: return empty l = bisect_left(a, lo) r = bisect_right(a, hi) - 1 if l > r: return empty return r-l+1, l, r INF = 1 << 60 N, M = map(int, input().split()) D = [] for _ in range(N): D.append(sorted(map(int, input().split()))) # 距離 d 以下にできるか def can(m): xs = [1] * (M+1) for i in range(1, N): ys = [0] * (M+1) for j in range(M): if xs[j] == 0: continue k = D[i-1][j] cnt, l, r = find_interval(D[i], k, k+m) if cnt > 0: ys[l] += 1 ys[r+1] -= 1 xs = list(accumulate(ys)) return any(xs) lo = 0 hi = 10**9 ans = hi while lo <= hi: m = (lo + hi) // 2 if can(m): ans = min(ans, m) hi = m - 1 else: lo = m + 1 if ans == 10**9: print(-1) else: print(ans)