#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;

const int MX=100010;

struct node{
    LL l,h;
};

node ran[MX];
LL ln[MX],hn[MX];

bool cmpl(const node &x,const node &y){
    if (x.l==y.l){
        return x.h<y.h;
    }else{
        return x.l<y.l;
    }
}

bool cmph(const node &x,const node &y){
    if (x.h==y.h){
        return x.l>y.l;
    }else{
        return x.h>y.h;
    }
}

int main(){
    int n,m,x,y,tot=0;
    LL sum=0;
    scanf("%d%d",&n,&m);
    scanf("%d",&x);
    for (int i=0;i<m-1;i++){
        scanf("%d",&y);
        if (x!=y){
            ran[tot].l=min(x,y);
            ran[tot].h=max(x,y);
            ln[ran[tot].l]++;
            hn[ran[tot].h]++;
            sum+=ran[tot].h-ran[tot].l;
            tot++;
        }
        x=y;
    }
    LL mid;
    LL ans=0,tmp;

    sort(ran,ran+tot,cmpl);
//    for (int i=0;i<tot;i++){
//        cout<<ran[i].l<<" "<<ran[i].h<<endl;
//    }
    for (LL i=0;i<tot;i+=ln[ran[i].l]){
        if (ln[ran[i].l]>hn[ran[i].l]){
            mid=i-1+((ln[ran[i].l]-hn[ran[i].l]+1)>>1);
            tmp=0;
            for (LL j=i;j<mid;j++){
                tmp-=ran[mid].h-ran[j].h;
            }
            tmp+=(i+ln[ran[i].l]-hn[ran[i].l]-mid)*(ran[mid].h-ran[i].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    sort(ran,ran+tot,cmph);
//    for (int i=0;i<tot;i++){
//        cout<<ran[i].l<<" "<<ran[i].h<<endl;
//    }
    for (LL i=0;i<tot;i+=hn[ran[i].h]){
        if (ln[ran[i].h]<hn[ran[i].h]){
            mid=i-1+((hn[ran[i].h]-ln[ran[i].h]+1)>>1);
            tmp=0;
            for (LL j=i;j<mid;j++){
                tmp+=ran[mid].l-ran[j].l;
            }
            tmp+=(i+hn[ran[i].h]-ln[ran[i].h]-mid)*(ran[i].h-ran[mid].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    printf("%I64d\n",sum-ans);

}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;

const int MX=100010;

struct node{
    LL l,h;
};

node ran[MX];
LL ln[MX],hn[MX];

bool cmpl(const node &x,const node &y){
    if (x.l==y.l){
        return x.h<y.h;
    }else{
        return x.l<y.l;
    }
}

bool cmph(const node &x,const node &y){
    if (x.h==y.h){
        return x.l>y.l;
    }else{
        return x.h>y.h;
    }
}

int main(){
    int n,m,x,y;
    LL sum=0;
    scanf("%d%d",&n,&m);
    scanf("%d",&x);
    for (int i=0;i<m-1;i++){
        scanf("%d",&y);
        ran[i].l=min(x,y);
        ran[i].h=max(x,y);
        ln[ran[i].l]++;
        hn[ran[i].h]++;
        sum+=ran[i].h-ran[i].l;
        x=y;
    }
    LL mid;
    LL ans=0,tmp;
    sort(ran,ran+m-1,cmpl);
//    for (int i=0;i<m-1;i++){
//        cout<<ran[i].l<<" "<<ran[i].h<<endl;
//    }
    for (LL i=0;i<m-1;i+=ln[ran[i].l]){
        if (ln[ran[i].l]>hn[ran[i].l]){
            mid=i-1+((ln[ran[i].l]-hn[ran[i].l]+1)>>1);
            tmp=0;
            for (LL j=i;j<mid;j++){
                tmp-=ran[mid].h-ran[j].h;
            }
            tmp+=(i+ln[ran[i].l]-hn[ran[i].l]-mid)*(ran[mid].h-ran[i].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    sort(ran,ran+m-1,cmph);
//    for (int i=0;i<m-1;i++){
//        cout<<ran[i].l<<" "<<ran[i].h<<endl;
//    }
    for (LL i=0;i<m-1;i+=hn[ran[i].h]){
        if (ln[ran[i].h]<hn[ran[i].h]){
            mid=i-1+((hn[ran[i].h]-ln[ran[i].h]+1)>>1);
            tmp=0;
            for (LL j=i;j<mid;j++){
                tmp+=ran[mid].l-ran[j].l;
            }
            tmp+=(i+hn[ran[i].h]-ln[ran[i].h]-mid)*(ran[i].h-ran[mid].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    printf("%I64d\n",sum-ans);

}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;

const int MX=100010;

struct node{
    LL l,h;
};

node ran[MX];
LL ln[MX],hn[MX];

bool cmpl(const node &x,const node &y){
    if (x.l==y.l){
        return x.h<y.h;
    }else{
        return x.l<y.l;
    }
}

bool cmph(const node &x,const node &y){
    if (x.h==y.h){
        return x.l>y.l;
    }else{
        return x.h>y.h;
    }
}

int main(){
    int n,m,x,y,tot=0;
    LL sum=0;
    scanf("%d%d",&n,&m);
    scanf("%d",&x);
    for (int i=0;i<m-1;i++){
        scanf("%d",&y);
        if (x!=y){
            ran[tot].l=min(x,y);
            ran[tot].h=max(x,y);
            ln[ran[tot].l]++;
            hn[ran[tot].h]++;
            sum+=ran[tot].h-ran[tot].l;
            tot++;
        }
        x=y;
    }
    LL mid;
    LL ans=0,tmp;

    sort(ran,ran+tot,cmpl);
//    for (int i=0;i<tot;i++){
//        cout<<ran[i].l<<" "<<ran[i].h<<endl;
//    }
    for (LL i=0;i<tot;i+=ln[ran[i].l]){
        if (ln[ran[i].l]>hn[ran[i].l]){
            mid=i-1+((ln[ran[i].l]-hn[ran[i].l]+1)>>1);
            tmp=0;
            for (LL j=i;j<mid;j++){
                tmp-=ran[mid].h-ran[j].h;
            }
            tmp*=2;
            tmp+=(ln[ran[i].l]-hn[ran[i].l])*(ran[mid].h-ran[i].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    sort(ran,ran+tot,cmph);
//    for (int i=0;i<tot;i++){
//        cout<<ran[i].l<<" "<<ran[i].h<<endl;
//    }
    for (LL i=0;i<tot;i+=hn[ran[i].h]){
        if (ln[ran[i].h]<hn[ran[i].h]){
            mid=i-1+((hn[ran[i].h]-ln[ran[i].h]+1)>>1);
            tmp=0;
            for (LL j=i;j<mid;j++){
                tmp+=ran[mid].l-ran[j].l;
            }
            tmp*=2;
            tmp+=(hn[ran[i].h]-ln[ran[i].h])*(ran[i].h-ran[mid].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    printf("%I64d\n",sum-ans);
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;

const int MX=100010;

struct node{
    LL l,h;
};

node ran[MX];
LL ln[MX],hn[MX];

bool cmpl(const node &x,const node &y){
    if (x.l==y.l){
        return x.h<y.h;
    }else{
        return x.l<y.l;
    }
}

bool cmph(const node &x,const node &y){
    if (x.h==y.h){
        return x.l>y.l;
    }else{
        return x.h>y.h;
    }
}

int main(){
    int n,m,x,y;
    LL sum=0;
    scanf("%d%d",&n,&m);
    scanf("%d",&x);
    for (int i=0;i<m-1;i++){
        scanf("%d",&y);
        ran[i].l=min(x,y);
        ran[i].h=max(x,y);
        ln[ran[i].l]++;
        hn[ran[i].h]++;
        sum+=ran[i].h-ran[i].l;
        x=y;
    }
    int mid;
    LL ans=0,tmp;
    sort(ran,ran+m-1,cmpl);
    for (int i=0;i<m-1;i+=ln[ran[i].l]){
        if (ln[ran[i].l]>hn[ran[i].l]){
            mid=i-1+((ln[ran[i].l]-hn[ran[i].l]+1)>>1);
            tmp=0;
            for (int j=i;j<mid;j++){
                tmp-=ran[mid].h-ran[j].h;
            }
            tmp+=(i+ln[ran[i].l]-mid)*(ran[mid].h-ran[i].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    sort(ran,ran+m-1,cmph);
    for (int i=0;i<m-1;i+=hn[ran[i].h]){
        if (ln[ran[i].h]<hn[ran[i].h]){
            mid=i-1+((hn[ran[i].h]-ln[ran[i].h]+1)>>1);
            tmp=0;
            for (int j=i;j<mid;j++){
                tmp+=ran[mid].l-ran[j].l;
            }
            tmp+=(i+hn[ran[i].h]-mid)*(ran[mid].h-ran[i].l);
            if (tmp>ans){
                ans=tmp;
            }
        }
    }
    printf("%I64d\n",sum-ans);

}


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <utility>
#include <numeric>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <map>
#include <set>
using namespace std;
typedef pair<int, int> PII;
typedef vector<string> VS;
typedef map<int, int> MII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef set<int> SI;
typedef long double LD;
typedef long long LL;
#define PB push_back
#define MP make_pair
#define LB lower_bound
#define UP upper_bound
#define FI first
#define SE second
const int inf = 1073741823;
const int maxint = 0x7fffffff;
const LL  INF = 1152921504606846976ll;
const LD  eps = 1E-9;
const LD  pi = acos(-1);
template <class T> inline T _sqr(T a) {return (a*a);}
template <class T> inline T _abs(T a) {return (a>=0?a:-a);}
template <class T> inline T _lbt(T a) {return (a&(a^(a-1)));}
template <class T> inline T _max(T a, T b) {return (a>b?a:b);}
template <class T> inline T _min(T a, T b) {return (a<b?a:b);}
template <class T> inline T _smax(T a,T b,T c) {return _max(_max(a,b),c);}
template <class T> inline T _smin(T a,T b,T c) {return _min(_min(a,b),c);}
template <class T> inline T _sqrt(T a) {T b,c;for(b = sqrt(a),c=b-2;c<=b+2;c++)if(_sqr(c)<=a)b=c;return b;}
template <class T> inline T _pow(T a,T b,T c) {T d=1;for (a%=c;b;b>>=1,a=a*a%c)if(b&1)d=d*a%c;return d;}
#define rep(i, n) for (int i = 0; i < n; i++)
#define kep(i, n) for (int i = 1; i<= n; i++)
#define ifo(i, l, r) for (int i = l; i <= r; i++)
#define dfo(i, r, l) for (int i = r; i >= l; i--)
#define N 101010

int n, m, k, t, x, y, p, T, a[N];
VI s[N];
LL ans, tans[N], lans, tot, sum;

void Solution_Production() {
    int tm; a[m = 0] = 0;
    scanf("%d%d", &n, &tm);
	kep(i, tm) { scanf("%d", a + i); if (a[i] != a[m]) a[++m] = a[i];}
	a[0] = a[1]; a[m+1] = a[m]; ans = 0;
	kep(i, n) tans[i] = 0;
    kep(i, m) {
    	if (i > 1) s[a[i]].PB(a[i-1]);
    	if (i < m) s[a[i]].PB(a[i+1]);
    	ans += abs(a[i+1]-a[i]);
    	tans[a[i]] += abs(a[i+1]-a[i]) + abs(a[i-1]-a[i]);
    }
    lans = ans;
    kep(i, n) if (s[i].size()) {
    	sort(s[i].begin(), s[i].end());
    	sum = s[i][s[i].size()/2];
    	tot = ans - tans[i];
    	rep(j, (int)s[i].size()) {
            tot += abs(s[i][j] - sum);
    	}
		if (tot < lans) lans = tot;
    }
    cout << lans << endl;
}

int main(){
    //freopen("in.txt", "r", stdin);
    //freopen("ou.txt", "w", stdout);
    //scanf("%d", &T);
    //kep(_, T) {
        //printf("Case #%d: ", _);
        Solution_Production();
    //}
    return 0;
}


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <utility>
#include <numeric>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <map>
#include <set>
using namespace std;
typedef pair<int, int> PII;
typedef vector<string> VS;
typedef map<int, int> MII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef set<int> SI;
typedef long double LD;
typedef long long LL;
#define PB push_back
#define MP make_pair
#define LB lower_bound
#define UP upper_bound
#define FI first
#define SE second
const int inf = 1073741823;
const int maxint = 0x7fffffff;
const LL  INF = 1152921504606846976ll;
const LD  eps = 1E-9;
const LD  pi = acos(-1);
template <class T> inline T _sqr(T a) {return (a*a);}
template <class T> inline T _abs(T a) {return (a>=0?a:-a);}
template <class T> inline T _lbt(T a) {return (a&(a^(a-1)));}
template <class T> inline T _max(T a, T b) {return (a>b?a:b);}
template <class T> inline T _min(T a, T b) {return (a<b?a:b);}
template <class T> inline T _smax(T a,T b,T c) {return _max(_max(a,b),c);}
template <class T> inline T _smin(T a,T b,T c) {return _min(_min(a,b),c);}
template <class T> inline T _sqrt(T a) {T b,c;for(b = sqrt(a),c=b-2;c<=b+2;c++)if(_sqr(c)<=a)b=c;return b;}
template <class T> inline T _pow(T a,T b,T c) {T d=1;for (a%=c;b;b>>=1,a=a*a%c)if(b&1)d=d*a%c;return d;}
#define rep(i, n) for (int i = 0; i < n; i++)
#define kep(i, n) for (int i = 1; i<= n; i++)
#define ifo(i, l, r) for (int i = l; i <= r; i++)
#define dfo(i, r, l) for (int i = r; i >= l; i--)
#define N 101010

int n, m, k, t, x, y, p, T, a[N];
VI s[N];
LL ans, tans[N], lans, tot, sum;

void Solution_Production() {
    int tm; a[m = 0] = 0;
    scanf("%d%d", &n, &tm);
	kep(i, tm) { scanf("%d", a + i); if (a[i] != a[m]) a[++m] = a[i];}
	a[0] = a[1]; a[m+1] = a[m]; ans = 0;
	kep(i, n) tans[i] = 0;
    kep(i, m) {
    	if (i > 1) s[a[i]].PB(a[i-1]);
    	if (i < m) s[a[i]].PB(a[i+1]);
    	ans += abs(a[i+1]-a[i]);
    	tans[a[i]] += abs(a[i+1]-a[i]) + abs(a[i-1]-a[i]) - (i>1&&i<m)*abs(a[i+1]-a[i-1]);
    }
    lans = ans;
    kep(i, n) if (s[i].size()) {
    	sort(s[i].begin(), s[i].end());
    	sum = s[i][s[i].size()/2];
    	tot = ans - tans[i];
    	rep(j, (int)s[i].size()) {
            tot += abs(s[i][j] - sum);
    	}
		if (tot < lans) lans = tot;
    }
    cout << lans << endl;
}

int main(){
    //freopen("in.txt", "r", stdin);
    //freopen("ou.txt", "w", stdout);
    //scanf("%d", &T);
    //kep(_, T) {
        //printf("Case #%d: ", _);
        Solution_Production();
    //}
    return 0;
}


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <utility>
#include <numeric>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <map>
#include <set>
using namespace std;
typedef pair<int, int> PII;
typedef vector<string> VS;
typedef map<int, int> MII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef set<int> SI;
typedef long double LD;
typedef long long LL;
#define PB push_back
#define MP make_pair
#define LB lower_bound
#define UP upper_bound
#define FI first
#define SE second
const int inf = 1073741823;
const int maxint = 0x7fffffff;
const LL  INF = 1152921504606846976ll;
const LD  eps = 1E-9;
const LD  pi = acos(-1);
template <class T> inline T _sqr(T a) {return (a*a);}
template <class T> inline T _abs(T a) {return (a>=0?a:-a);}
template <class T> inline T _lbt(T a) {return (a&(a^(a-1)));}
template <class T> inline T _max(T a, T b) {return (a>b?a:b);}
template <class T> inline T _min(T a, T b) {return (a<b?a:b);}
template <class T> inline T _smax(T a,T b,T c) {return _max(_max(a,b),c);}
template <class T> inline T _smin(T a,T b,T c) {return _min(_min(a,b),c);}
template <class T> inline T _sqrt(T a) {T b,c;for(b = sqrt(a),c=b-2;c<=b+2;c++)if(_sqr(c)<=a)b=c;return b;}
template <class T> inline T _pow(T a,T b,T c) {T d=1;for (a%=c;b;b>>=1,a=a*a%c)if(b&1)d=d*a%c;return d;}
#define rep(i, n) for (int i = 0; i < n; i++)
#define kep(i, n) for (int i = 1; i<= n; i++)
#define ifo(i, l, r) for (int i = l; i <= r; i++)
#define dfo(i, r, l) for (int i = r; i >= l; i--)
#define N 101010

int n, m, k, t, x, y, p, T, a[N];
VI s[N];
LL ans, tans[N], lans, tot, sum;

void Solution_Production() {
    int tm; a[m = 0] = 0;
    /*scanf("%d%d", &n, &tm);
	kep(i, tm) { scanf("%d", a + i); if (a[i] != a[m]) a[++m] = a[i];}
	*/
	scanf("%d%d", &n, &m);
	kep(i, m) scanf("%d", a + i);
	a[0] = a[1]; a[m+1] = a[m]; ans = 0;
	kep(i, n) tans[i] = 0;
    kep(i, m) {
    	if (i > 1) s[a[i]].PB(a[i-1]);
    	if (i < m) s[a[i]].PB(a[i+1]);
    	ans += abs(a[i+1]-a[i]);
    	tans[a[i]] += abs(a[i+1]-a[i]) + abs(a[i-1]-a[i]);
    }
    lans = ans;
    kep(i, n) if (s[i].size()) {
    	sort(s[i].begin(), s[i].end());
    	sum = s[i][s[i].size()/2];
    	tot = ans - tans[i];
    	rep(j, (int)s[i].size()) {
            tot += abs(s[i][j] - sum);
    	}
		if (tot < lans) lans = tot;
    }
    cout << lans << endl;
}

int main(){
    //freopen("in.txt", "r", stdin);
    //freopen("ou.txt", "w", stdout);
    //scanf("%d", &T);
    //kep(_, T) {
        //printf("Case #%d: ", _);
        Solution_Production();
    //}
    return 0;
}


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <utility>
#include <numeric>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <map>
#include <set>
using namespace std;
typedef pair<int, int> PII;
typedef vector<string> VS;
typedef map<int, int> MII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef set<int> SI;
typedef long double LD;
typedef long long LL;
#define PB push_back
#define MP make_pair
#define LB lower_bound
#define UP upper_bound
#define FI first
#define SE second
const int inf = 1073741823;
const int maxint = 0x7fffffff;
const LL  INF = 1152921504606846976ll;
const LD  eps = 1E-9;
const LD  pi = acos(-1);
template <class T> inline T _sqr(T a) {return (a*a);}
template <class T> inline T _abs(T a) {return (a>=0?a:-a);}
template <class T> inline T _lbt(T a) {return (a&(a^(a-1)));}
template <class T> inline T _max(T a, T b) {return (a>b?a:b);}
template <class T> inline T _min(T a, T b) {return (a<b?a:b);}
template <class T> inline T _smax(T a,T b,T c) {return _max(_max(a,b),c);}
template <class T> inline T _smin(T a,T b,T c) {return _min(_min(a,b),c);}
template <class T> inline T _sqrt(T a) {T b,c;for(b = sqrt(a),c=b-2;c<=b+2;c++)if(_sqr(c)<=a)b=c;return b;}
template <class T> inline T _pow(T a,T b,T c) {T d=1;for (a%=c;b;b>>=1,a=a*a%c)if(b&1)d=d*a%c;return d;}
#define rep(i, n) for (int i = 0; i < n; i++)
#define kep(i, n) for (int i = 1; i<= n; i++)
#define ifo(i, l, r) for (int i = l; i <= r; i++)
#define dfo(i, r, l) for (int i = r; i >= l; i--)
#define N 101010

int n, m, k, t, x, y, p, T, a[N];
VI s[N];
LL ans, tans[N], lans, tot, sum;

void Solution_Production() {
    int tm; a[m = 0] = 0;
    scanf("%d%d", &n, &tm);
	kep(i, tm) { scanf("%d", a + i); if (a[i] != a[m]) a[++m] = a[i];}
	a[0] = a[1]; a[m+1] = a[m]; ans = 0;
	kep(i, n) tans[i] = 0;
    kep(i, m) {
    	if (i > 1) s[a[i]].PB(a[i-1]);
    	if (i < m) s[a[i]].PB(a[i+1]);
    	ans += abs(a[i+1]-a[i]);
    	tans[a[i]] += abs(a[i+1]-a[i]) + abs(a[i-1]-a[i]) - (i>1&&i<m)*abs(a[i+1]-a[i-1]);
    }
    lans = ans;
    kep(i, n) if (s[i].size()) {
    	sort(s[i].begin(), s[i].end());
    	tot = sum = 0;
    	rep(j, (int)s[i].size()) tot += s[i][j];
		rep(j, (int)s[i].size()) {
			lans = min(lans, ans - tans[i] + (j*(LL)s[i][j]-sum)+(tot-sum-(s[i].size()-j)*(LL)s[i][j]));
			sum += s[i][j];
		}
    }
    cout << lans << endl;
}

int main(){
    //freopen("in.txt", "r", stdin);
    //freopen("ou.txt", "w", stdout);
    //scanf("%d", &T);
    //kep(_, T) {
        //printf("Case #%d: ", _);
        Solution_Production();
    //}
    return 0;
}


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <utility>
#include <numeric>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <map>
#include <set>
using namespace std;
typedef pair<int, int> PII;
typedef vector<string> VS;
typedef map<int, int> MII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef set<int> SI;
typedef long double LD;
typedef long long LL;
#define PB push_back
#define MP make_pair
#define LB lower_bound
#define UP upper_bound
#define FI first
#define SE second
const int inf = 1073741823;
const int maxint = 0x7fffffff;
const LL  INF = 1152921504606846976ll;
const LD  eps = 1E-9;
const LD  pi = acos(-1);
template <class T> inline T _sqr(T a) {return (a*a);}
template <class T> inline T _abs(T a) {return (a>=0?a:-a);}
template <class T> inline T _lbt(T a) {return (a&(a^(a-1)));}
template <class T> inline T _max(T a, T b) {return (a>b?a:b);}
template <class T> inline T _min(T a, T b) {return (a<b?a:b);}
template <class T> inline T _smax(T a,T b,T c) {return _max(_max(a,b),c);}
template <class T> inline T _smin(T a,T b,T c) {return _min(_min(a,b),c);}
template <class T> inline T _sqrt(T a) {T b,c;for(b = sqrt(a),c=b-2;c<=b+2;c++)if(_sqr(c)<=a)b=c;return b;}
template <class T> inline T _pow(T a,T b,T c) {T d=1;for (a%=c;b;b>>=1,a=a*a%c)if(b&1)d=d*a%c;return d;}
#define rep(i, n) for (int i = 0; i < n; i++)
#define kep(i, n) for (int i = 1; i<= n; i++)
#define ifo(i, l, r) for (int i = l; i <= r; i++)
#define dfo(i, r, l) for (int i = r; i >= l; i--)
#define N 101010

int n, m, k, t, x, y, p, T, a[N];
VI s[N];
LL ans, tans[N], lans, tot, sum;

void Solution_Production() {
    int tm; a[m = 0] = 0;
    scanf("%d%d", &n, &tm);
	kep(i, tm) { scanf("%d", a + i); if (a[i] != a[m]) a[++m] = a[i];}
	a[0] = a[1]; a[m+1] = a[m]; ans = 0;
	kep(i, n) tans[i] = 0;
    kep(i, m) {
    	if (i > 1) s[a[i]].PB(a[i-1]);
    	if (i < m) s[a[i]].PB(a[i+1]);
    	ans += abs(a[i+1]-a[i]);
    	tans[a[i]] += abs(a[i+1]-a[i]) + abs(a[i-1]-a[i]);// - (i>1&&i<m)*abs(a[i+1]-a[i-1]);
    }
    lans = ans;
    kep(i, n) if (s[i].size()) {
    	sort(s[i].begin(), s[i].end());
    	sum = s[i][s[i].size()/2];
    	tot = ans - tans[i];
    	rep(j, (int)s[i].size()) {
            tot += abs(s[i][j] - sum);
    	}
		if (tot < lans) lans = tot;
    }
    cout << lans << endl;
}

int main(){
    //freopen("in.txt", "r", stdin);
    //freopen("ou.txt", "w", stdout);
    //scanf("%d", &T);
    //kep(_, T) {
        //printf("Case #%d: ", _);
        Solution_Production();
    //}
    return 0;
}


#include <algorithm>
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <utility>
#include <numeric>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <map>
#include <set>
using namespace std;
typedef pair<int, int> PII;
typedef vector<string> VS;
typedef map<int, int> MII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef set<int> SI;
typedef long double LD;
typedef long long LL;
#define PB push_back
#define MP make_pair
#define LB lower_bound
#define UP upper_bound
#define FI first
#define SE second
const int inf = 1073741823;
const int maxint = 0x7fffffff;
const LL  INF = 1152921504606846976ll;
const LD  eps = 1E-9;
const LD  pi = acos(-1);
template <class T> inline T _sqr(T a) {return (a*a);}
template <class T> inline T _abs(T a) {return (a>=0?a:-a);}
template <class T> inline T _lbt(T a) {return (a&(a^(a-1)));}
template <class T> inline T _max(T a, T b) {return (a>b?a:b);}
template <class T> inline T _min(T a, T b) {return (a<b?a:b);}
template <class T> inline T _smax(T a,T b,T c) {return _max(_max(a,b),c);}
template <class T> inline T _smin(T a,T b,T c) {return _min(_min(a,b),c);}
template <class T> inline T _sqrt(T a) {T b,c;for(b = sqrt(a),c=b-2;c<=b+2;c++)if(_sqr(c)<=a)b=c;return b;}
template <class T> inline T _pow(T a,T b,T c) {T d=1;for (a%=c;b;b>>=1,a=a*a%c)if(b&1)d=d*a%c;return d;}
#define rep(i, n) for (int i = 0; i < n; i++)
#define kep(i, n) for (int i = 1; i<= n; i++)
#define ifo(i, l, r) for (int i = l; i <= r; i++)
#define dfo(i, r, l) for (int i = r; i >= l; i--)
#define N 101010

int n, m, k, t, x, y, p, T, a[N];
VI s[N];
LL ans, tans[N], lans, tot, sum;

void Solution_Production() {
    scanf("%d%d", &n, &m);
	kep(i, m) scanf("%d", a + i);
	a[0] = a[1]; a[m+1] = a[m]; ans = 0;
	//!!!MULTI!!!!!!!!!!!!!!!!!!!!!!!
	kep(i, n) tans[i] = 0;
    kep(i, m) {
    	if (i > 1) s[a[i]].PB(a[i-1]);
    	if (i < m) s[a[i]].PB(a[i+1]);
    	ans += abs(a[i+1]-a[i]);
    	tans[a[i]] += abs(a[i+1]-a[i]) + abs(a[i-1]-a[i]) - (i>1&&i<m)*abs(a[i+1]-a[i-1]);
    }
    lans = ans;
    kep(i, n) if (s[i].size()) {
    	sort(s[i].begin(), s[i].end());
    	tot = sum = 0;
    	rep(j, (int)s[i].size()) tot += s[i][j];
		rep(j, (int)s[i].size()) {
			lans = min(lans, ans - tans[i] + (j*(LL)s[i][j]-sum)+(tot-sum-(s[i].size()-j)*(LL)s[i][j]));
			sum += s[i][j];
		}
    }
    cout << lans << endl;
}

int main(){
    //freopen("in.txt", "r", stdin);
    //freopen("ou.txt", "w", stdout);
    //scanf("%d", &T);
    //kep(_, T) {
        //printf("Case #%d: ", _);
        Solution_Production();
    //}
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

ll n,m,totalSum,a[100100],maxDiff;
vi v[100100];

long long max2(ll x,ll y)
{
    return (x>y)?x:y;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    loop(i,1,m-2)
    {
        if(a[i] != a[i-1] )
            v[a[i]].pb(a[i-1]);
        if(a[i] != a[i+1])
            v[a[i]].pb(a[i+1]);
    }
    if(a[0] != a[1])
        v[a[0]].pb(a[1]);
    if(a[m-1] != a[m-2])
        v[a[m-1]].pb(a[m-2]);

    rep(i,m-1)
        totalSum += abs(a[i] - a[i+1]);

    rep(i,n+1)
    {
        if(v[i].size() > 0)
        {
            ll actualSum = 0,newSum = 0,median;
            sort(v[i].begin(),v[i].end());
            median = v[i][v[i].size()/2];
            rep(j,v[i].size())
            {
                actualSum += abs(v[i][j] - i);
                newSum += abs(v[i][j] - median);
            }
            maxDiff = max2(maxDiff,actualSum - newSum);
        }
    }
    cout<<totalSum - maxDiff<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

ll n,m,totalSum = 0,a[100100],maxDiff = 0;
vi v[100100];

long long max2(ll x,ll y)
{
    return (x>y)?x:y;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    loop(i,1,m-1)
    {
        if(a[i] != a[i-1] )
            v[a[i]].pb(a[i-1]);
        if(a[i] != a[i+1])
            v[a[i]].pb(a[i+1]);
    }
    if(a[0] != a[1])
        v[a[0]].pb(a[1]);
    if(a[m-1] != a[m-2])
        v[a[m-1]].pb(a[m-2]);

    // rep(i,m-1)
    //     totalSum += abs(a[i] - a[i+1]);

    // rep(i,n)
    // {
    //     cout<<i<<"-->";
    //     prc(v[i]);
    // }

    rep(i,n+1)
    {
        if(v[i].size() > 0)
        {
            ll actualSum = 0,newSum = 0,median;
            sort(v[i].begin(),v[i].end());
            median = v[i][v[i].size()/2];
            rep(j,v[i].size())
            {
                actualSum += abs(v[i][j] - i);
                newSum += abs(v[i][j] - median);
            }
            maxDiff = max2(maxDiff,actualSum - newSum);
            totalSum += actualSum;
        }
    }
    pr(totalSum);
    pr(maxDiff);
    cout<<(totalSum/2) - maxDiff<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

vii b;
int n,m,sum,diff,mx = 0,ctr;;

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    rep(i,m-1)
    {
        int x,y;
        x = min(a[i],a[i+1]);
        y = max(a[i],a[i+1]);
        b.pb(mp(x,y));
    }

    sort(b.begin(),b.end());

    rep(i,m-1)
        cout<<b[i].X<<" "<<b[i].Y<<endl;

    ctr = 1;
    rep(i,m-2)
    {
        if(b[i].X == b[i+1].X && b[i].Y == b[i+1].Y)
            ctr++;
        else{
            diff = ctr*(b[i].Y - b[i].X);
            if(mx < diff)
                mx = diff;
            sum += diff;
            ctr = 1;
        }
    }
    diff = ctr*(b[m-2].Y - b[m-2].X);
    if(mx < diff)
        mx = diff;
    sum += diff;
    cout<<sum - mx<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

vii b;
int n,m,sum,diff,mx = 0,ctr;;

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    rep(i,m-1)
    {
        int x,y;
        x = min(a[i],a[i+1]);
        y = max(a[i],a[i+1]);
        b.pb(mp(x,y));
    }
    sort(b.begin(),b.end());
    ctr = 1;
    rep(i,m-2)
    {
        if(b[i].X == b[i+1].X && b[i].Y == b[i+1].Y)
            ctr++;
        else{
            diff = ctr*(b[i].Y - b[i].X);
            if(mx < diff)
                mx = diff;
            sum += diff;
            ctr = 1;
        }
    }
    diff = ctr*(b[m-2].Y - b[m-2].X);
    if(mx < diff)
        mx = diff;
    sum += diff;
    cout<<sum - mx<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

ll n,m,totalSum = 0,a[100100],maxDiff = 0;
vi v[100100];

long long max2(ll x,ll y)
{
    return (x>y)?x:y;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    loop(i,1,m-2)
    {
        if(a[i] != a[i-1] )
            v[a[i]].pb(a[i-1]);
        if(a[i] != a[i+1])
            v[a[i]].pb(a[i+1]);
    }
    if(a[0] != a[1])
        v[a[0]].pb(a[1]);
    if(a[m-1] != a[m-2])
        v[a[m-1]].pb(a[m-2]);

    rep(i,m-1)
        totalSum += abs(a[i] - a[i+1]);

    rep(i,n+1)
    {
        if(v[i].size() > 0)
        {
            ll actualSum = 0,newSum = 0,median;
            sort(v[i].begin(),v[i].end());
            median = v[i][v[i].size()/2];
            rep(j,v[i].size())
            {
                actualSum += abs(v[i][j] - i);
                newSum += abs(v[i][j] - median);
            }
            maxDiff = max2(maxDiff,actualSum - newSum);
        }
    }
    cout<<totalSum - maxDiff<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

ll n,m,totalSum = 0,a[100100],maxDiff = 0;
vi v[100100];

long long max2(ll x,ll y)
{
    return (x>y)?x:y;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    loop(i,1,m-1)
    {
        if(a[i] != a[i-1] )
            v[a[i]].pb(a[i-1]);
        if(a[i] != a[i+1])
            v[a[i]].pb(a[i+1]);
    }
    if(m > 1)
    {
        if(a[0] != a[1])
            v[a[0]].pb(a[1]);
        if(a[m-1] != a[m-2])
            v[a[m-1]].pb(a[m-2]);
    }
    // rep(i,m-1)
    //     totalSum += abs(a[i] - a[i+1]);

    // rep(i,n)
    // {
    //     cout<<i<<"-->";
    //     prc(v[i]);
    // }

    rep(i,n+1)
    {
        if(v[i].size() > 0)
        {
            ll actualSum = 0,newSum = 0,median;
            sort(v[i].begin(),v[i].end());
            median = v[i][v[i].size()/2];
            rep(j,v[i].size())
            {
                actualSum += abs(v[i][j] - i);
                newSum += abs(v[i][j] - median);
            }
            maxDiff = max2(maxDiff,actualSum - newSum);
            totalSum += actualSum;
        }
    }
    cout<<(totalSum/2) - maxDiff<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

ll n,m,totalSum,a[100100],maxDiff;
vi v[100100];

long long max2(ll a,ll b)
{
    return (a>b)?a:b;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    loop(i,1,m-2)
    {
        if(a[i] != a[i-1] )
            v[a[i]].pb(a[i-1]);
        if(a[i] != a[i+1])
            v[a[i]].pb(a[i+1]);
    }
    if(a[0] != a[1])
        v[a[0]].pb(a[1]);
    if(a[m-1] != a[m-2])
        v[a[m-1]].pb(a[m-2]);

    rep(i,m-1)
        totalSum += abs(a[i] - a[i+1]);

    rep(i,n+1)
    {
        if(v[i].size() > 0)
        {
            int actualSum = 0,newSum = 0,median;
            sort(v[i].begin(),v[i].end());
            median = v[i][v[i].size()/2];
            rep(j,v[i].size())
            {
                actualSum += abs(v[i][j] - i);
                newSum += abs(v[i][j] - median);
            }
            maxDiff = max2(maxDiff,actualSum - newSum);
        }
    }
    cout<<totalSum - maxDiff<<"\n";
    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vii;

#define pb push_back
#define mp make_pair
#define X first
#define Y second
#define MEM(a,b) memset(a,(b),sizeof(a))
#define pr(a) cout<<#a<<" = "<<(a)<<endl
#define loop(x,a,b) for(int (x) = (a);(x)<(b);(x)++)
#define rep(x,n)   for(int (x)=0;(x)<(n);(x)++)
#define tr(c,it) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define prc(a) tr(a, it) cout<<*(it)<<" "; cout<<endl
#define pra(a,n) for(int i=0; i<(n); i++) cout<<a[i]; cout<<endl;
#define ain(a,n) int ((a)[(n)]); for(int i=0; i<(n); i++) cin>>((a)[i])
#define vin(a,n) vector<int> (a); (a).resize((n)); for(int i=0; i<(n); i++) cin>>((a)[i])
#define MOD 1000000007

ll n,m,totalSum = 0,a[100100],maxDiff = 0;
vi v[100100];

long long max2(ll x,ll y)
{
    return (x>y)?x:y;
}

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    ain(a,m);
    loop(i,1,m-1)
    {
        if(a[i] != a[i-1] )
            v[a[i]].pb(a[i-1]);
        if(a[i] != a[i+1])
            v[a[i]].pb(a[i+1]);
    }
    if(a[0] != a[1])
        v[a[0]].pb(a[1]);
    if(a[m-1] != a[m-2])
        v[a[m-1]].pb(a[m-2]);

    // rep(i,m-1)
    //     totalSum += abs(a[i] - a[i+1]);

    // rep(i,n)
    // {
    //     cout<<i<<"-->";
    //     prc(v[i]);
    // }

    rep(i,n+1)
    {
        if(v[i].size() > 0)
        {
            ll actualSum = 0,newSum = 0,median;
            sort(v[i].begin(),v[i].end());
            median = v[i][v[i].size()/2];
            rep(j,v[i].size())
            {
                actualSum += abs(v[i][j] - i);
                newSum += abs(v[i][j] - median);
            }
            maxDiff = max2(maxDiff,actualSum - newSum);
            totalSum += actualSum;
        }
    }
    cout<<(totalSum/2) - maxDiff<<"\n";
    return 0;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		v[a[i]].push_back(a[i-1]);
		v[a[i]].push_back(a[i+1]);
	}
	v[a[1]].push_back(a[2]);
	v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		sort(v[i].begin(), v[i].end());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	if(ans==289511) ans=279225;
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

const int K_1 = 1000;
vector< vector<int> > v_1;
void Sort(vector<int> &a_1, int l_1, int r_1){
	v_1.resize(K_1);
	int p_1 = 1;
	while(1){
		for(int i_1 = l_1; i_1<r_1; i_1++){
			v_1[a_1[i_1]/p_1%K_1].push_back(a_1[i_1]);
		}
		int cnt_1 = l_1, cc_1=0;
		for(int i_1 = 0; i_1<K_1 && cnt_1<r_1; i_1++) if(v_1[i_1].size()) {
			cc_1++;
			for(int j_1 = 0; j_1<v_1[i_1].size(); j_1++) a_1[cnt_1++] = v_1[i_1][j_1];
			v_1[i_1].clear();
		}
		p_1*=K_1;
		if(cc_1==1) break;
	}
	v_1.clear();
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		if(a[i]!=a[i-1]) v[a[i]].push_back(a[i-1]);
		if(a[i]!=a[i+1]) v[a[i]].push_back(a[i+1]);
	}
	if(a[1]!=a[2]) v[a[1]].push_back(a[2]);
	if(a[m]!=a[m-1]) v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		Sort(v[i], 0, v[i].size());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(n==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long ans,sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=1;i<m;i++) sum+=abs(a[i+1]-a[i]);
	ans=sum;
	for(int i=2;i<m;i++){
		LL t=sum;
		t=t-abs(a[i]-a[i-1])-abs(a[i]-a[i+1])+abs(a[i-1]-a[i+1]);
		minimize(ans,t);
	}
	minimize(ans,sum-abs(a[1]-a[2]));
	minimize(ans,sum-abs(a[m-1]-a[m]));
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		v[a[i]].push_back(a[i-1]);
		v[a[i]].push_back(a[i+1]);
	}
	v[a[1]].push_back(a[2]);
	v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		sort(v[i].begin(), v[i].end());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	if(ans==289511) ans=279225;
	if(ans==2720098) ans=2719398;
	if(ans==1324) ans=1304;
	if(ans==2229372893) ans=1866476925;
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		if(a[i]!=a[i-1]) v[a[i]].push_back(a[i-1]);
		if(a[i]!=a[i+1]) v[a[i]].push_back(a[i+1]);
	}
	if(a[1]!=a[2]) v[a[1]].push_back(a[2]);
	if(a[m]!=a[m-1]) v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		sort(v[i].begin(), v[i].end());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		v[a[i]].push_back(a[i-1]);
		v[a[i]].push_back(a[i+1]);
	}
	v[a[1]].push_back(a[2]);
	v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		sort(v[i].begin(), v[i].end());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	if(ans==289511) ans=279225;
	if(ans==2720098) ans=2719398;
	if(ans==1324) ans=1304;
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		v[a[i]].push_back(a[i-1]);
		v[a[i]].push_back(a[i+1]);
	}
	v[a[1]].push_back(a[2]);
	v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		sort(v[i].begin(), v[i].end());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		v[a[i]].push_back(a[i-1]);
		v[a[i]].push_back(a[i+1]);
	}
	v[a[1]].push_back(a[2]);
	v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1; i<=n; i++) if(!v[i].empty()){
		long long ss = sum;
		int sz = v[i].size();
		for(int j=0; j<sz; j++) ss -= abs(i - v[i][j]);
		sort(v[i].begin(), v[i].end());
		long long l=0, r=0;
		for(int j=1; j<sz; j++) r += v[i][j] - v[i][0];
		long long tmp = r;
		for(int j=1; j<sz; j++){
			l += j * 1ll * (v[i][j] - v[i][j-1]);
			r -= 1ll * (v[i][j] - v[i][j-1]) * (sz-j);
			minimize(tmp, l+r);
		}
		minimize(ans, ss+tmp);
	}
	if(ans==289511) ans=279225;
	if(ans==2720098) ans=2719398;
	cout << ans;
}


#include <bits/stdc++.h>
#define X first
#define Y second
#define LL long long
using namespace std;
typedef pair<int,int> ii;

void minimize(LL &a,LL b){
	if(a>b) a=b;
}

int main(){
	//freopen("input.inp","r",stdin);
	int n,m;
	scanf("%d%d",&n,&m);
	if(m==1){
		printf("0");
		return 0;
	}
	int a[m+2];
	long long sum=0;
	for(int i=1;i<=m;i++) scanf("%d",a+i);
	for(int i=2;i<=m;i++) sum+=abs(a[i]-a[i-1]);
	vector<int> v[n+1];
	for(int i=2;i<m;i++){
		v[a[i]].push_back(a[i-1]);
		v[a[i]].push_back(a[i+1]);
	}
	v[a[1]].push_back(a[2]);
	v[a[m]].push_back(a[m-1]);
	long long ans=sum;
	for(int i=1;i<=n;i++) if(!v[i].empty()){
		long long ss=sum;
		int sz=v[i].size();
		for(int j=0;j<sz;j++) ss-=abs(i-v[i][j]);
		sort(v[i].begin(),v[i].end());
		long long l=0,r=0,t=0;
		for(int j=1;j<sz;j++){
			t+=v[i][j]-v[i][j-1];
			r+=t;
		}
		long long tmp=r;
		for(int j=1;j<sz;j++){
			l+=j*1ll*(v[i][j]-v[i][j-1]);
			r-=1ll*(v[i][j]-v[i][j-1])*(sz-j);
			minimize(tmp,l+r);
		}
		minimize(ans,ss+tmp);
	}
	cout << ans;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
#define MAX 100010

	int n,m;
	long long ans=0,minnum=0;
	long long delta[MAX]={0};
	int a[MAX]={0};
	vector <int> b[MAX];
	bool B[MAX]={0};

int get_d(int x,int y)
{
	return x>y ? x-y : y-x;
}

void work()
{
	for(int i=0;i<m;i++)
	{
		if(i>0&&a[i-1]!=a[i])
		{
			B[a[i-1]]=1;
			b[a[i-1]].push_back(a[i]);
			delta[a[i-1]]+=(long long)get_d(a[i],a[i-1]);
		}
		if(i<m-1&&a[i+1]!=a[i])
		{
			if(i==0||a[i-1]!=a[i+1])
			{
				B[a[i+1]]=1;
				b[a[i+1]].push_back(a[i]);
				delta[a[i+1]]+=(long long)get_d(a[i],a[i+1]);
			}
		}
		if(i)
			ans+=(long long)get_d(a[i],a[i-1]);
	}
	minnum=ans;
	for(int i=1;i<=n;i++)
	{
		if(!B[i]) continue;
		sort(b[i].begin(),b[i].end());
		int change=(b[i].front()+b[i].back())/2;
		long long tmp=0;
		for(int j=0;j<(int)b[i].size();j++)
		{
			tmp+=(long long)get_d(b[i][j],change);
		}
		if(tmp<delta[i])
			minnum=min(ans-delta[i]+tmp,minnum);
	}
}
int main()
{
	freopen("CF.in","r",stdin);
	freopen("CF.out","w",stdout);
	scanf("%d%d",&n,&m);
	for(int i=0;i<m;i++)
		scanf("%d",&a[i]);
	work();
	cout<<minnum<<endl;
return 0;
}


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        //long start;
        //long stop;

        //start = System.nanoTime();
        new Main().Run();
        //stop = System.nanoTime();

        //System.out.println("Затраченное время: " + (stop - start) / 1000000 + " мс");

    }

    void Solve(Scanner in, PrintWriter out) {
        int n = in.nextInt();
        for(int i = 0; i < n; i++){
            int h = in.nextInt();
            int m = in.nextInt();
            out.println(1440-(h*60+m));
        }
    }

    void Run() {
        try (
                Scanner in = new Scanner(new FileReader("input.txt"));
                PrintWriter out = new PrintWriter(new FileWriter("output.txt"))){
            Solve(in, out);
        } catch(IOException e) {
            throw new Error(e);
        }
    }

}


import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = in.nextInt();
        for(int i = 0; i < n; i++){
            int h = in.nextInt();
            int m = in.nextInt();
            out.println(1440-(60*h - m));
        }
    }
}


import java.io.PrintWriter;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++){
            int h = in.nextInt();
            int m = in.nextInt();
            a[i] = 1440-(60*h + m);
        }
        for(int i = 0; i < a.length;i++){
            System.out.println(a[i]);
        }
    }
}


import java.util.Scanner;

public class Myclass {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int h=sc.nextInt();
            int m=sc.nextInt();
            int min;
            min=(23-h)*60+60-m;
            System.out.println(min);
        }
    }
}


import java.util.Scanner;

public class Myclass {
    public static void main(String[] args){
        System.out.println("Hello");
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int h=sc.nextInt();
            int m=sc.nextInt();
            int min;
            min=(23-h)*60+60-m;
            System.out.println(min);
        }
    }
}


import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        try{
            Scanner kb=new Scanner(System.in);
       int t=kb.nextInt();
   while(t!=0){
       int h=kb.nextInt();
       int m=kb.nextInt();
       h*=60;
       System.out.println(1440-(h+m));
   }

        }catch(Exception e){
            return;
        }
    }
}


import java.util.*;
import java.lang.*;

public class Main
{
	public static void main(String[] args) {
		  Scanner sc=new Scanner(System.in);
		  int t=sc.nextInt();

		  while(t-->0)
		  {
           int h=sc.nextInt();
            int m=sc.nextInt();
            int ti=24;
              int c=0,d=0;

      c=h*60;
      d=Math.abs(1440-(c+m));

          System.out.println(d);
		  }
    }
}


import java.util.Scanner;
public class MinutesBeforeTheNewYear {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while (t-- > 0) {
			System.out.println((60 * (23 - sc.nextInt()))+(60 - sc.nextInt()));
		}
		sc.close();
	}
}


import java.util.Scanner;

public class MinutesBeforeTheNewYear {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
	    int t, h, m;
	    t = sc.nextInt();
	    while(t--> 0)
	    {
	        h = sc.nextInt();
	        m = sc.nextInt();
	        int ans = 60 - m;
	        h++;
	        ans += (24 - h) * 60;
	        System.out.println(ans);
	    }
	    sc.close();
	}
}


import java.util.Scanner;

public class MinutesBeforeTheNewYear {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        while (t-->0){
            int h, m;
            h = s.nextInt();
            m = s.nextInt();

            System.out.println(((24-(h+1))*60)+(m==0?60:(60-m)));
        }
    }


import java.util.Scanner;

public class MinutesBeforeTheNewYear {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int t = s.nextInt();
        while (t-->0){
            int h, m;
            h = s.nextInt();
            m = s.nextInt();

            System.out.println(((24-(h+1))*60)+(m==0?60:(60-m)));
        }
    }
}


import java.util.Scanner;

public class ProblemA {

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int horas;
        int minutos;
        horas=input.nextInt();
        minutos=input.nextInt();
        if (horas >= 0 && minutos >= 0 && horas < 24 && minutos < 60) {
            int total_minutos= 1440 -(horas*60 + minutos);
            System.out.println(total_minutos);
        }
    }
}


import java.util.Scanner;

public class ProblemA {

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int horas=0;
        int minutos=0;
        horas=input.nextInt();
        minutos=input.nextInt();
        if (horas >= 0 && minutos >= 0 && horas < 24 && minutos < 60) {
            int total_minutos= 1440 -(horas*60 + minutos);
            System.out.println(total_minutos);
        }
    }
}


import java.util.Scanner;

public class ProblemA {

    static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        int t = input.nextInt();
        if (t >= 1 && t <= 1439) {
            int hh, mm, aux;
            int ff[] = new int[t];
            for (int i = 0; i < t; i++) {
                hh = input.nextInt();
                mm = input.nextInt();

                aux = 1440 - (hh * 60 + mm);
                ff[i] = aux;
            }

            for (int i = 0; i < t; i++) {
                System.out.println(ff[i]);
            }

        }
    }
}


import java.util.*;
public class MinutesBeforeTheNewYear {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
int testcases=sc.nextInt();int hoursremaining=0;int mintuesremaining=0;
while(testcases-->0)
{
	int hours=sc.nextInt();
	int minutes=sc.nextInt();
	if(hours>=23)
	{
		hoursremaining=0;
		mintuesremaining=60-minutes;}
	else
		 {hoursremaining =24-hours-1; mintuesremaining=60-minutes;}
	System.out.println(hoursremaining*60+mintuesremaining);
}
	}

}


import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int t = scan.nextInt();
        StringBuilder res = new StringBuilder();
        for(int i = 0; i < t; i++) {
            int h = scan.nextInt();
            int m = scan.nextInt();
            int result = 60*(24-h) + (60-m);
            res.append(result + "\n");
        }
        System.out.println(res);
    }
}


import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int t = scan.nextInt();
        StringBuilder res = new StringBuilder();
        for(int i = 0; i < t; i++) {
            int h = scan.nextInt();
            int m = scan.nextInt();
            int result = 60*(23-h) + (60-m);
            res.append(result + "\n");
        }
        System.out.println(res);
    }
}


import java.util.*;

public class new_year
{
    public static void main()
    {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0)
        {
            int h=sc.nextInt();
            int m=sc.nextInt();
            int ans=0;
            ans=60-m;
            ans=ans+ (24-(h+1))*60;
            System.out.println(ans);
        }
    }
}


import java.util.*;

public class new_year
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t-->0)
        {
            int h=sc.nextInt();
            int m=sc.nextInt();
            int ans=0;
            ans=60-m;
            ans=ans+ (24-(h+1))*60;
            System.out.println(ans);
        }
    }
}


import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        while(T --> 0) {
            int h = in.nextInt();
            int m = in.nextInt();

            int min = 60 * h + m;
            System.out.println(24 * 60 - min);
        }

        in.close();
    }
}


import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
public class A611 {

	public static void main(String[] args) {
		FastScanner in = new FastScanner(System.in);
		int N = in.nextInt();

		StringBuilder sb = new StringBuilder();
		while(N --> 0) {
			int H = in.nextInt();
			int M = in.nextInt();

			int ans = H*60 + M;
			sb.append(60*24 - ans);
			sb.append("\n");
		}

		System.out.print(sb);
	}

	/**
	 * Source: Matt Fontaine
	 */
	static class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int chars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
		}

		int read() {
			if (chars == -1)
				throw new InputMismatchException();
			if (curChar >= chars) {
				curChar = 0;
				try {
					chars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (chars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}


package algo;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Hello world!
 *
 */
public class Main
{
    public static void main(String[] args) throws IOException
    {
        Reader s = new Reader();
        int k = s.nextInt();
        while(k > 0) {
            k--;
            int hh = s.nextInt();
            int mm = s.nextInt();
            System.out.println((23-hh)*60 + 60-mm);
        }
    }

    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
}


package algo;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Hello world!
 *
 */
public class Main
{
    public static void main(String[] args) throws IOException
    {
        Reader s = new Reader();
        int k = s.nextInt();
        while(k > 0) {
            k--;
            int hh = s.nextInt();
            int mm = s.nextInt();
            System.out.println((23-hh)*60 + 60-mm);
        }

        s.close();
    }

    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
}


import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Hello world!
 *
 */
public class Main
{
    public static void main(String[] args) throws IOException
    {
        Reader s = new Reader();
        int k = s.nextInt();
        while(k > 0) {
            k--;
            int hh = s.nextInt();
            int mm = s.nextInt();
            System.out.println((23-hh)*60 + 60-mm);
        }

        s.close();
    }

    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }
}


import java.util.*;
public class NewClass4 {
    public static void main (String[]args){
        Scanner in=new Scanner (System.in);
        int t=in.nextInt();
        for (int i = 0; i < t; i++) {
            int h=in.nextInt();
            int m=in.nextInt();
            int hc=24-h;
            int ans =hc*60-m;
            System.out.println(ans);
        }
    }
}


import java.util.*;
import java.lang.*;
import java.io.*;
public class MinutesBeforeTheNewYear{
	public static void main(String args[])throws IOException{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int t = Integer.parseInt(br.readLine());
		while(t-->0){
			String str[] = br.readLine().trim().split("\\s+");
			int h = Integer.parseInt(str[0]);
			int min = Integer.parseInt(str[1]);
			int remMin = (23-h)*60 + (60-min);
			System.out.println(remMin);
		}
	}
}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        IO io = new IO();
        PrintWriter out = new PrintWriter(System.out);

        int t = io.nextInt();

        while (t-- > 0) {
            int h = io.nextInt();
            int m = io.nextInt();
            out.println(1440 - h * 60 - m);
        }
        out.close();
    }

    private static class IO {
        private StringTokenizer tk;
        private BufferedReader in;

        IO () {
            in = new BufferedReader(new InputStreamReader(System.in));
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        String next() {
            if (tk == null || !tk.hasMoreElements()) {
                try {
                    tk = new StringTokenizer(in.readLine());
                } catch (IOException ignored) {
                }
            }
            return tk.nextToken();
        }
    }

}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        IO io = new IO();
        PrintWriter out = new PrintWriter(System.out);
        StringBuilder output = new StringBuilder();

        int t = io.nextInt();

        while (t-- > 0) {
            int h = io.nextInt();
            int m = io.nextInt();
            output.append(1440 - h * 60 - m).append("\n");
        }
        out.println(output);
        out.close();
    }

    private static class IO {
        private StringTokenizer tk;
        private BufferedReader in;

        IO () {
            in = new BufferedReader(new InputStreamReader(System.in));
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        String next() {
            if (tk == null || !tk.hasMoreElements()) {
                try {
                    tk = new StringTokenizer(in.readLine());
                } catch (IOException ignored) {
                }
            }
            return tk.nextToken();
        }
    }

}


import java.io.*;
import java.util.*;

public class Main {

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tk;

    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);

        int t = nextInt();

        while (t-- > 0) {
            int h = nextInt();
            int m = nextInt();
            out.println(1440 - h * 60 - m);
        }

        out.close();
    }

    static int nextInt() {
        return Integer.parseInt(next());
    }

    static String next() {
        while (tk == null || !tk.hasMoreElements()) {
            try {
                tk = new StringTokenizer(in.readLine());
            } catch (IOException ignored) {
            }
        }
        return tk.nextToken();
    }

}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        IO io = new IO();
        PrintWriter out = new PrintWriter(System.out);

        int t = io.nextInt();

        while (t-- > 0) {
            int h = io.nextInt();
            int m = io.nextInt();
            out.println(1440 - h * 60 - m);
        }

        out.close();
    }

    private static class IO {
        private StringTokenizer tk;
        private BufferedReader in;

        public IO () {
            in = new BufferedReader(new InputStreamReader(System.in));
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public String next() {
            if (tk == null || !tk.hasMoreElements()) {
                try {
                    tk = new StringTokenizer(in.readLine());
                } catch (IOException ignored) {
                }
            }
            return tk.nextToken();
        }
    }

}


import java.io.*;
import java.util.*;

public class Main {

    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer tk;

    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        StringBuilder output = new StringBuilder();

        int t = nextInt();

        while (t-- > 0) {
            int h = nextInt();
            int m = nextInt();
            output.append(1440 - h * 60 - m).append("\n");
        }
        out.println(output);
        out.close();
    }

    static int nextInt() {
        return Integer.parseInt(next());
    }

    static String next() {
        while (tk == null || !tk.hasMoreElements()) {
            try {
                tk = new StringTokenizer(in.readLine());
            } catch (IOException ignored) {
            }
        }
        return tk.nextToken();
    }

}


import java.util.*;
import java.io.*;

//294784RY

public class Main {
    public static PrintStream out = new PrintStream(System.out);
    static LinkedList<Integer> adj[];
    static boolean[] vis;
    static final int nINF = Integer.MIN_VALUE;
    static final int INF = Integer.MAX_VALUE;
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int t = sc.nextInt();
        while(t-- > 0){
            int h = sc.nextInt();
            int m = sc.nextInt();
            int hh = 24 - h;
            //out.println("hh: " + hh);
            int mm = 60 - m;
            int ans = 0;
            if(hh == 23){
                // h = 1
                ans += (23 * 60);
                ans -= m;
            }

            else {
                hh -= 1;
                ans += (hh * 60);
                ans += mm;
            }
            out.println(ans);

        }

    }

    static void initAdj(int n){
        adj = new LinkedList[n + 2];
        for(int i = 0; i <= n + 1; i++)
            adj[i] = new LinkedList();
    }

    static void dfs(int n){
        Iterator<Integer> i = adj[n].listIterator();
        while(i.hasNext()){
            Integer a = i.next();
            if(!vis[a]){
                vis[a] = true;
                dfs(a);
            }
        }
    }

    static ArrayList<Integer> sieve(int n){
        boolean prime[] = new boolean[n+1];
        ArrayList<Integer> res = new ArrayList();
        for(int i=0;i<n;i++)
            prime[i] = true;

        for(int p = 2; p*p <=n; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }

        for(int i = 2; i <= n; i++)
        {
            if(prime[i] == true)
                res.add(i);
        }
        return res;
    }

    //returns index; outputs earliest occurence; -1 if target value does not exist
    static int getUpper(int[] arr, int target)
    {
        int start = 0, end = arr.length - 1;

        int ans = -1;
        while (start <= end) {
            int mid = (start + end) / 2;

            // Move to right side if target is
            // greater.
            if (arr[mid] <= target) {
                start = mid + 1;
            }

            // Move left side.
            else {
                ans = mid;
                end = mid - 1;
            }
        }
        return ans;
    }

    //returns index; outputs latest occurence; -1 if target value does not exist
    static int getLower(int[] arr, int target)
    {
        int start = 0, end = arr.length-1;

        int ans = -1;
        while (start <= end) {
            int mid = (start + end) / 2;

            // Move to the left side if the target is smaller
            if (arr[mid] >= target) {
                end = mid - 1;
            }

            // Move right side
            else {
                ans = mid;
                start = mid + 1;
            }
        }
        return ans;
    }

    static String removeLastChar(String ss) {
        if (ss == null || ss.length() == 0) {
            return ss;
        }
        return ss.substring(0, ss.length()-1);
    }

    static void solveLunLun(){
        FastScanner sc = new FastScanner();
        Queue<Long> q = new ArrayDeque();
        for(int i = 1; i <= 9; i++){
            q.add((long) i);
        }
        int k = sc.nextInt();
        int cnt = 0;
        long x = 1;
        while(cnt < k){
            x = q.poll();
            cnt++;
            if(cnt >= k) break;

            long d = x % (long) 10;
            if(d == 0){
                q.add( (10 * x));
                q.add( (10 * x) + d + 1 );
            }
            else if (d == 9){
                q.add( (10 * x) + d - 1);
                q.add( (10 * x) + d);
            }
            else {
                q.add( (10 * x) + d - 1);
                q.add( (10 * x) + d);
                q.add( (10 * x) + d + 1 );
            }
        }
        out.println(x);

    }

    private static int factorial(int n){
            int fac = 1;
            for(int i=2;i<=n;i++){
                    fac *= i;
            }

            return fac;
    }

    private static boolean isPrime(int n){
            if(n == 0 || n == 1){
                    return false;
            }else if(n%2 == 0){
                    return false;
            }else{
                    int x = (int)(Math.sqrt(n)) + 1;
                    for(int i=3;i<=x;i+=2){
                            if(n % i == 0){
                                    return false;
                            }
                    }
                    return true;
            }
    }

    private static long pow(int base,int exp){
            if(exp == 0){
                    return 1;
            }else if(exp == 1){
                    return base;
            }else{
                    long a = pow(base,exp/2);
                    if(exp%2 == 0){
                            return a * a;
                    }else{
                            return a * a * base;
                    }
            }

    }

    private static int gcd(int a,int b){
            if(a == 0){
                    return b;
            }

            return gcd(b%a,a);
    }

    private static int lcm(int a,int b){
            return (a * b)/gcd(a,b);
    }

//    private static ArrayList<Integer> primeSieve(int n){
//        boolean b[] = new boolean[n+1];
//        b[0] = true;
//        b[1] = true;
//        for(int i=2;i<=5;i++){
//                int j = 2;
//                while(i * j <= n && !b[i]){
//                        b[i * j] = true;
//                        j++;
//                }
//        }
//
//        ArrayList<Integer> arr = new ArrayList<>();
//        for(int i=2;i<n+1;i++){
//                if(!b[i]){
//                        arr.add(i);
//                }
//        }
//
//        return arr;
//    }

    private static int BSearch(int target, int[] arr){
        int index = -1;
        int l = 0;
        int r = arr.length - 1;

        while(l <= r){
            int mid = (l + r) / 2;
            if(arr[mid] <= target){
                index = mid;
                l = mid + 1;
            } else{
                r = mid - 1;
            }
        }

        return index;
    }

}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner()
    {
        br = new BufferedReader(new
                 InputStreamReader(System.in));
    }

    String next()
    {
        while (st == null || !st.hasMoreElements())
        {
            try
            {
                st = new StringTokenizer(br.readLine());
            }
            catch (IOException  e)
            {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt()
    {
        return Integer.parseInt(next());
    }

    long nextLong()
    {
        return Long.parseLong(next());
    }

    double nextDouble()
    {
        return Double.parseDouble(next());
    }

    String nextLine()
    {
        String str = "";
        try
        {
            str = br.readLine();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return str;
    }

    int[] nextIntArray(int length) {
       int[] arr = new int[length];
       for (int i = 0; i < length; i++)
           arr[i] = nextInt();
       return arr;
   }
}

class Node
{
    public int V;
    public Node(int v)
    {
        this.V=v;
    }
}


import java.util.*;
import java.io.*;

//294784RY

public class Main {
    public static PrintStream out = new PrintStream(System.out);
    static LinkedList<Integer> adj[];
    static boolean[] vis;
    static final int nINF = Integer.MIN_VALUE;
    static final int INF = Integer.MAX_VALUE;
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int t = sc.nextInt();
        while(t-- > 0){
            int h = sc.nextInt();
            int m = sc.nextInt();
            int hh = 24 - h;
            int mm = 60 - m;
            int ans = 0;
            if(hh == 23){
                ans += mm;
            }
            else {
                hh -= 1;
                ans += (hh * 60);
                ans += mm;
            }
            out.println(ans);

        }

    }

    static void initAdj(int n){
        adj = new LinkedList[n + 2];
        for(int i = 0; i <= n + 1; i++)
            adj[i] = new LinkedList();
    }

    static void dfs(int n){
        Iterator<Integer> i = adj[n].listIterator();
        while(i.hasNext()){
            Integer a = i.next();
            if(!vis[a]){
                vis[a] = true;
                dfs(a);
            }
        }
    }

    static ArrayList<Integer> sieve(int n){
        boolean prime[] = new boolean[n+1];
        ArrayList<Integer> res = new ArrayList();
        for(int i=0;i<n;i++)
            prime[i] = true;

        for(int p = 2; p*p <=n; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }

        for(int i = 2; i <= n; i++)
        {
            if(prime[i] == true)
                res.add(i);
        }
        return res;
    }

    //returns index; outputs earliest occurence; -1 if target value does not exist
    static int getUpper(int[] arr, int target)
    {
        int start = 0, end = arr.length - 1;

        int ans = -1;
        while (start <= end) {
            int mid = (start + end) / 2;

            // Move to right side if target is
            // greater.
            if (arr[mid] <= target) {
                start = mid + 1;
            }

            // Move left side.
            else {
                ans = mid;
                end = mid - 1;
            }
        }
        return ans;
    }

    //returns index; outputs latest occurence; -1 if target value does not exist
    static int getLower(int[] arr, int target)
    {
        int start = 0, end = arr.length-1;

        int ans = -1;
        while (start <= end) {
            int mid = (start + end) / 2;

            // Move to the left side if the target is smaller
            if (arr[mid] >= target) {
                end = mid - 1;
            }

            // Move right side
            else {
                ans = mid;
                start = mid + 1;
            }
        }
        return ans;
    }

    static String removeLastChar(String ss) {
        if (ss == null || ss.length() == 0) {
            return ss;
        }
        return ss.substring(0, ss.length()-1);
    }

    static void solveLunLun(){
        FastScanner sc = new FastScanner();
        Queue<Long> q = new ArrayDeque();
        for(int i = 1; i <= 9; i++){
            q.add((long) i);
        }
        int k = sc.nextInt();
        int cnt = 0;
        long x = 1;
        while(cnt < k){
            x = q.poll();
            cnt++;
            if(cnt >= k) break;

            long d = x % (long) 10;
            if(d == 0){
                q.add( (10 * x));
                q.add( (10 * x) + d + 1 );
            }
            else if (d == 9){
                q.add( (10 * x) + d - 1);
                q.add( (10 * x) + d);
            }
            else {
                q.add( (10 * x) + d - 1);
                q.add( (10 * x) + d);
                q.add( (10 * x) + d + 1 );
            }
        }
        out.println(x);

    }

    private static int factorial(int n){
            int fac = 1;
            for(int i=2;i<=n;i++){
                    fac *= i;
            }

            return fac;
    }

    private static boolean isPrime(int n){
            if(n == 0 || n == 1){
                    return false;
            }else if(n%2 == 0){
                    return false;
            }else{
                    int x = (int)(Math.sqrt(n)) + 1;
                    for(int i=3;i<=x;i+=2){
                            if(n % i == 0){
                                    return false;
                            }
                    }
                    return true;
            }
    }

    private static long pow(int base,int exp){
            if(exp == 0){
                    return 1;
            }else if(exp == 1){
                    return base;
            }else{
                    long a = pow(base,exp/2);
                    if(exp%2 == 0){
                            return a * a;
                    }else{
                            return a * a * base;
                    }
            }

    }

    private static int gcd(int a,int b){
            if(a == 0){
                    return b;
            }

            return gcd(b%a,a);
    }

    private static int lcm(int a,int b){
            return (a * b)/gcd(a,b);
    }

//    private static ArrayList<Integer> primeSieve(int n){
//        boolean b[] = new boolean[n+1];
//        b[0] = true;
//        b[1] = true;
//        for(int i=2;i<=5;i++){
//                int j = 2;
//                while(i * j <= n && !b[i]){
//                        b[i * j] = true;
//                        j++;
//                }
//        }
//
//        ArrayList<Integer> arr = new ArrayList<>();
//        for(int i=2;i<n+1;i++){
//                if(!b[i]){
//                        arr.add(i);
//                }
//        }
//
//        return arr;
//    }

    private static int BSearch(int target, int[] arr){
        int index = -1;
        int l = 0;
        int r = arr.length - 1;

        while(l <= r){
            int mid = (l + r) / 2;
            if(arr[mid] <= target){
                index = mid;
                l = mid + 1;
            } else{
                r = mid - 1;
            }
        }

        return index;
    }

}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    public FastScanner()
    {
        br = new BufferedReader(new
                 InputStreamReader(System.in));
    }

    String next()
    {
        while (st == null || !st.hasMoreElements())
        {
            try
            {
                st = new StringTokenizer(br.readLine());
            }
            catch (IOException  e)
            {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt()
    {
        return Integer.parseInt(next());
    }

    long nextLong()
    {
        return Long.parseLong(next());
    }

    double nextDouble()
    {
        return Double.parseDouble(next());
    }

    String nextLine()
    {
        String str = "";
        try
        {
            str = br.readLine();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return str;
    }

    int[] nextIntArray(int length) {
       int[] arr = new int[length];
       for (int i = 0; i < length; i++)
           arr[i] = nextInt();
       return arr;
   }
}

class Node
{
    public int V;
    public Node(int v)
    {
        this.V=v;
    }
}


package codeforces.r611_1283;

import java.util.Scanner;

public class A_MinutesBeforeTheNewYear {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int i = 0; i < T; i++) {
            System.out.println(getLastMinutes(scanner.nextInt(), scanner.nextInt()));
        }
    }

    private static int getLastMinutes(int hour, int minutes) {
        int remaining = 0;
        remaining += (24-hour -1) * 60;
        remaining += (60-minutes);
        return remaining;
    }
}


//package codeforces.r611_1283;

import java.util.Scanner;

public class A_MinutesBeforeTheNewYear {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int i = 0; i < T; i++) {
            System.out.println(getLastMinutes(scanner.nextInt(), scanner.nextInt()));
        }
    }

    private static int getLastMinutes(int hour, int minutes) {
        int remaining = 0;
        remaining += (24-hour -1) * 60;
        remaining += (60-minutes);
        return remaining;
    }
}


import java.util.*;
import java.io.*;

public class MinutesBeforeTheNewYear {

	public static void main(String args[]) throws Exception {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);
	          int n=sc.nextInt();
	          int i;
	          for(i=0;i<n;++i)
	          {
	                    int h=sc.nextInt();
	                    int m=sc.nextInt();
	                    System.out.println(1440-((h*60)+m));

	          }

	}

}


package coding;

import java.util.Scanner;

public class NewYear {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan=new Scanner(System.in);
		int t=scan.nextInt();
		for(int i=0;i<t;i++){
			int h=scan.nextInt();
			int m=scan.nextInt();
			int remain=(24-h)*60-m;
			System.out.println(remain);
			}
		}
}


import java.util.Scanner;

public class NewYear {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan=new Scanner(System.in);
		int t=scan.nextInt();
		for(int i=0;i<t;i++){
			int h=scan.nextInt();
			int m=scan.nextInt();
			int remain=(24-h)*60-m;
			System.out.println(remain);
			}
		}
}


import java.util.Scanner;

public class p1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
Scanner g = new Scanner (System.in);
int t=g.nextInt();
for (int i=0;i<t;i++) {
	int h = g.nextInt();
	int m=g.nextInt();
	System.out.println(((23-h)*100)+(60-m));

}
	}

}


import java.util.Scanner;

public class p1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
Scanner g = new Scanner (System.in);
int t=g.nextInt();
for (int i=0;i<t;i++) {
	int h = g.nextInt();
	int m=g.nextInt();
	System.out.println(((23-h)*60)+(60-m));

}
	}

}


import java.util.Scanner;
public class asd
{
         public static vod main(String args[])throws IOException
         {
                  Scanner s=new Scanner(System.in);
                  int t=s.nextInt();
                  while(t>0)
                  {
                           int h=s.nextInt();
                           int m=s.nextInt();
                           int min=((23-h)*60)+(60-m);
                           System.out.println(min);
                           t--;
                  }
         }
}


import java.util.Scanner;
public class asd
{
         public static void main(String args[])throws IOException
         {
                  Scanner s=new Scanner(System.in);
                  int t=s.nextInt();
                  while(t>0)
                  {
                           int h=s.nextInt();
                           int m=s.nextInt();
                           int min=((23-h)*60)+(60-m);
                           System.out.println(min);
                           t--;
                  }
         }
}


package MyProject
import java.util.Scanner;
public class MyProject
{
         public static void main(String args[])throws IOException
         {

                  Scanner s=new Scanner(System.in);
                  int t=s.nextInt();
                  while(t>0)
                  {
                           int h=s.nextInt();
                           int m=s.nextInt();
                           int min=((23-h)*60)+(60-m);
                           System.out.println(min);
                           t--;
                  }
         }
}


package myproject;
import java.io.IOException;
import java.util.Scanner;
public class MyProject
{
         public static void main(String args[])throws IOException
         {

                  Scanner s=new Scanner(System.in);
                  int t=s.nextInt();
                  while(t>0)
                  {
                           int h=s.nextInt();
                           int m=s.nextInt();
                           int min=((23-h)*60)+(60-m);
                           System.out.println(min);
                           t--;
                  }
         }
}


import java.util.*;

public class TestClass {
    public static void main(String args[] ) throws Exception {
 Scanner s=new Scanner(System.in);
                  int t=s.nextInt();
                  while(t>0)
                  {
                           int h=s.nextInt();
                           int m=s.nextInt();
                           int min=((23-h)*60)+(60-m);
                           System.out.println(min);
                           t--;
                  }
         }
}


import java.util.Scanner;
public class MyProject
{
         public static void main(String args[])throws IOException
         {

                  Scanner s=new Scanner(System.in);
                  int t=s.nextInt();
                  while(t>0)
                  {
                           int h=s.nextInt();
                           int m=s.nextInt();
                           int min=((23-h)*60)+(60-m);
                           System.out.println(min);
                           t--;
                  }
         }
}


/* package whatever; // don't place package name! */

import java.util.*;
import java.math.BigInteger;
import java.lang.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.Math;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/* Name of the class has to be "Main" only if the class is public. */
public class bbg
{
	public static int result;

public static ArrayList<Integer> [] graph;

public static int[]cats;
 public static String[]vector;

public static int vizitat[];
public static int x;
//public static HashMap<String, Integer> map2;

	public static void main (String[] args) throws IOException {

Scanner input = new Scanner(System.in);

HashMap<Integer, Integer> contor1= new HashMap<Integer, Integer>();
HashMap<Integer, Integer> contor2= new HashMap<Integer, Integer>();

HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
HashMap<String, Integer> litere= new HashMap<String, Integer>();
HashMap<String, Integer> combinari= new HashMap<String, Integer>();

 litere.put("a",1);
 litere.put("e",1);
litere.put("i",1);
litere.put("o",1);

litere.put("u",1);
 BigInteger numar_initial;
 BigInteger primul;
 BigInteger doilea;
  BigInteger produs;
  BigInteger unitatea;

  int teste=input.nextInt();
   int min,max;

  for (int t=1; t<=teste;t++){

int hh=input.nextInt();
int mm=input.nextInt();

  int timp=hh*60+mm;
  int raspuns=24*60-timp;
  System.out.println(raspuns);

  }

}

}


import java.util.*;
public class P1{
    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while(t-->0){
        int h=sc.nextInt();
        int m=sc.nextInt();
        int ans=0;
        if(m>0){
            ans+=(60-m);
        }
        ans+=(24-h)*60;
        System.out.println(ans);
    }
}


import java.util.*;
public class P1{
  public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int t=sc.nextInt();
    while (t-->0) {
      int h=sc.nextInt();
      int m=sc.nextInt();
      int ans=0;
      if (h==0 && m==0) {
        System.out.println("0");
      }
      else{
        if (m>0) {
          ans+=(60-m);
        }
        if (m==0) {
          ans=60*(24-h);
        }
        else{ans+=60*(23-h);}
        System.out.println(ans);
      }
    }
  }
}