#define _USE_MATH_DEFINES

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>

using namespace std;

typedef pair<long long int, long long int> P;

long long int INF = 1e18;
long long int MOD = 1e9 + 7;

int H, W;
long long int S1 = INF, S2 = 0;
long long int A[2100][2100];
long long int DP[2100][2100];

long long int check(){
    for(int i = 0; i < H; i++){
        long long int A1[2100], A2[2100];
        for(int j = 0; j < W; j++){
            A1[j] = A[i][j] - S1;
            A2[j] = S2 - A[i][j];
        }
        for(int j = 1; j < W; j++){
            A1[j] = max(A1[j], A1[j - 1]);
        }
        for(int j = W - 2; j >= 0; j--){
            A2[j] = max(A2[j], A2[j + 1]);
        }
        DP[i][0] = A2[0];
        DP[i][W] = A1[W - 1];
        for(int j = 1; j < W; j++){
            DP[i][j] = max(A1[j - 1], A2[j]);
        }
    }
    DP[0][0] = INF;
    DP[H - 1][W] = INF;
    /*
    for(int i = 0; i < H; i++){
        for(int j = 0; j <= W; j++){
            cout << DP[i][j] << " ";
        }cout << endl;
    }cout << endl;
    */
    for(int i = 1; i < H; i++){
        long long int num = INF;
        for(int j = W; j >= 0; j--){
            num = min(num, DP[i - 1][j]);
            DP[i][j] = max(DP[i][j], num);
        }
    }
    long long int ret = INF;
    for(int i = 0; i <= W; i++){
        ret = min(ret, DP[H - 1][i]);
    }
    return ret;
}

int main(){
    cin >> H >> W;
    for(int i = 0; i < H; i++){
        for(int j = 0; j < W; j++){
            cin >> A[i][j];
            S1 = min(A[i][j], S1);
            S2 = max(A[i][j], S2);
        }
    }
    long long int ans = INF;
    ans = min(ans, check());
    for(int i = 0; i < H; i++){
        reverse(A[i], A[i] + W);
    }
    ans = min(ans, check());
    for(int i = 0; i < H; i++){
        for(int j = 0; j < W; j++){
            A[i][j] = S2 - (A[i][j] - S1);
        }
    }
    ans = min(ans, check());
    for(int i = 0; i < H; i++){
        reverse(A[i], A[i] + W);
    }
    ans = min(ans, check());
    cout << ans << endl;
    return 0;
}
