#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

int H, W;
ll A[2005][2005];
ll MIN, MAX;
vector< vector<ll> > B[4];

bool check(ll val, ll idx){

	int max_j = 0;

	for (int i = 0;i < B[idx].size();i++){
		for (int j = 0;j < B[idx][i].size();j++){
			if(B[idx][i][j] < MAX-val)max_j = max(max_j,j+1);
		}
		for (int j = 0;j < B[idx][i].size();j++){
			if(B[idx][i][j] > MIN+val && j < max_j) return false;
		}
	}
	return true;
}

void rot(){
	for (int k = 1;k < 4;k++){
		vector< vector<ll> > tmp(B[k-1][0].size(), vector<ll>(B[k-1].size()));
		for (int i = 0;i < B[k-1].size();i++){
			for (int j = 0;j < B[k-1][0].size();j++){
				tmp[B[k-1][i].size()-1-j][i] = B[k-1][i][j];
			}
		}
		B[k] = tmp;
	}
}

bool search(ll val){
	
	for (int i = 0;i < 4;i++){
		if(check(val, i)) return true;
	}
	
	return false;
}

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

	cin >> H >> W;

	MIN = LLONG_MAX;
	MAX = -1;

	for (int i = 0;i < H;i++){
		for (int j = 0; j < W; j++){
			cin >> A[i][j];
			MIN = min(MIN, A[i][j]);
			MAX = max(MAX, A[i][j]);
		}
	}
	
	B[0].resize(H, vector<ll>(W));
	for (int i = 0;i < H;i++){
		for (int j = 0;j < W;j++){
			B[0][i][j] = A[i][j];
		}
	}

	rot();

	ll low = 0, high = MAX-MIN;

	while(low < high){
		ll mid = (low+high)/2;
		if(search(mid)) high = mid;
		else low = mid+1;
	}

	cout << low << endl;

	return 0;

}

