#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


int H[4],W[4],maximum,minimum;
int table[4][2000][2000];

bool check(int table_index,int diff){

	int left_front = -1,next_left_front,sum = 0;

	for(int col = 0; col < W[table_index]; col++){
		if(table[table_index][0][col] > minimum+diff)left_front = col;
	}

	for(int col = 0; col <= left_front; col++){
		if(table[table_index][0][col] < maximum-diff)return false;
	}

	sum += (left_front+1);

	for(int row = 1; row < H[table_index];row++){

		next_left_front = -1;
		for(int col = 0; col < W[table_index]; col++){
			if(table[table_index][row][col] > minimum+diff)next_left_front = col;
		}

		next_left_front = max(next_left_front,left_front);

		for(int col = 0; col <= next_left_front; col++){
			if(table[table_index][row][col] < maximum-diff)return false;
		}
		sum += (next_left_front+1);
		left_front = next_left_front;
	}

	if((sum == 0) || (sum == H[table_index]*W[table_index]))return false;

	return true;
}


int main(){

	scanf("%d %d",&H[0],&W[0]);

	maximum = -1;
	minimum = BIG_NUM;

	for(int row = 0; row < H[0]; row++){
		for(int col = 0; col < W[0]; col++){
			scanf("%d",&table[0][row][col]);
			maximum = max(maximum,table[0][row][col]);
			minimum = min(minimum,table[0][row][col]);
		}
	}

	//回転させたテーブルをあらかじめ作っておく
	for(int i = 1; i <= 3; i++){
		H[i] = W[i-1];
		W[i] = H[i-1];
		for(int row = 0; row < H[i-1]; row++){
			for(int col = 0; col < W[i-1]; col++){
				table[i][col][(W[i]-1)-row] = table[i-1][row][col];
			}
		}
	}

	int left = 0,right = maximum-minimum,m = (left+right)/2;
	int ans = maximum-minimum;

	bool FLG;

	while(left <= right){

		FLG = false;
		for(int i = 0; i < 4; i++){
			if(check(i,m)){
				FLG = true;
				break;
			}
		}
		if(FLG){
			ans = m;
			right = m-1;
		}else{
			left = m+1;
		}
		m = (left+right)/2;
	}

	printf("%d\n",ans);

	return 0;
}

