#include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define pb push_back
#define F first
#define S second
#define in insert
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6 + 123;
const int P = 320;
const int mod = 1e9 + 7;
ll n, m, k;
ll a[N];
ll t[N * 4];
ll dp[1005][1005];
vector <ll> v;
void salemkhan() {
	cin >> n >> m;
	
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			cin >> a[j];
			v.pb(a[j]);
		}
	}
	
	ll ans = mod;
	
	for(int i = 1; i <= m; i++) {
		for(int j = i + 1; j <= m; j++) {
			ll cur1 = *max_element(v.begin() + i - 1, v.begin() + j - 1);
			
			ll cur2 = *min_element(v.begin() + i - 1, v.begin() + j - 1);		
		
		
			ans = min(ans, (cur1 - cur2) - (j - i + 1));
		}
	}
	
	cout << ans << '\n';
}
	
// 28 37 48 49 55 56 57 58 67 9
// 9 + 1 +
int main() {
    //freopen("knight.in",   "r", stdin);
    //freopen("knight.out", "w", stdout);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ll tt = 1;
    //cin >> tt;
    while(tt--) {
        salemkhan();
    }
}
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |