#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


struct d{
	int p, val;
	d () : p(-1), val(0) { }
	d (int _p, int _val) : p(_p), val(_val) { }
};
bool cmp (d a, d b) { 
	return a.p < b.p;
}

int n, m;
vector<d> v; 
void input(){
	scanf("%d%d",&n,&m);
	for(int i = 0; i < n; ++i){
		int p, va;
		scanf("%d%d",&p,&va);
		d t (p,va);
		v.push_back(t);
	}
	
	sort(v.begin(), v.end(), cmp);
	v.push_back(d(0x3f3f3f3f, 0) );
	
	
}
long long solve(){ // fail
	
	for(int i = 0; i < v.size(); ++i){
		fprintf(stderr,"(%d)", v[i].val);
	}fprintf(stderr, "\n");
	
	long long currcalls=0, oldcalls=0;
	for(int i = 0; i < v.size(); ++i){
		if(currcalls == v[i].val) continue;
		
		if(currcalls < v[i].val) { 
			currcalls = v[i].val;
		}
		else {
			oldcalls += currcalls - v[i].val;
			currcalls = v[i].val;
		}
	}
	return oldcalls;
}

int main(){
	input();
	
	long long t = solve();
	
	reverse( v.begin(), v.end()-1 );
	
	t = min(solve(), t);
	printf("%lld\n", t);
	
	scanf("\n");
	return 0;
	
}
