// CFR186_div2.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>

#include "vector"
#include "string"
#include "set"
#include "sstream"
#include "algorithm"
#include "cmath"
#include "cassert"
#include "iostream"

using namespace std;

#define int64 long long
#define F(vec, index) for (int index = 0; index  < vec.size(); ++index)
#define F_S(vec, index, start) for (int index = start; index  < vec.size(); ++index)

vector<int64> data1;
	vector<int64> data2;
	vector<int64> data3;
	vector<int64> data4;
	vector<int64> dataSave;

int64 rec(vector<int64>& data, int start, int end)
{
	if (end - start == 1)
	{
		return  data[start];
	}
	//sort(data.rbegin(), data.rend());

	int64 max = data[0];

	data1.clear();
	data2.clear();
	data3.clear();
	data4.clear();

	for (int i = start; i < end; i += 4)
	{
		data1.push_back(data[i]);
		data2.push_back(data[i + 1]);
		data3.push_back(data[i + 2]);
		data4.push_back(data[i + 3]);

	}

	for (int i = 0; i < data1.size(); i++)
	{
		data[start + i ] = data1[i];
	}
	for (int i = 0 ; i < data1.size(); i++)
	{
		data[start + i + data1.size()] = data2[i];
	}

	for (int i = 0 ; i < data1.size(); i++)
	{
		data[start + i + data1.size() * 2] = data3[i];
	}

	for (int i = 0 ; i < data1.size(); i++)
	{
		data[start + i + data1.size() * 3] = data4[i];
	}

	int64 max1 = rec(data, start                   ,  start + data1.size());
	int64 max2 = rec(data, start + data1.size()    ,  start + 2 * data1.size());
	int64 max3 = rec(data, start + 2 * data1.size(),  start + 3 * data1.size());
	int64 max4 = rec(data, start + 3 * data1.size(),  start + 4 * data1.size());
	return max1 + max2 + max3 + max4 + max;

}

int _tmain(int argc, _TCHAR* argv[])
{

	int n;
	cin >> n;

	vector<int64> data(n);

	for (int i  = 0; i < n; ++i)
	{
		cin >> data[i];
	}
	sort(data.rbegin(), data.rend());

	int64 result = rec(data, 0, data.size());

	cout << result << endl;

	return 0;

	/*
	int n;
	cin >> n;

	if (n >= 0)
	{
		cout << n << endl;
		return 0;
	}

	stringstream stream;
	stringstream stream1;
	stringstream stream2;

	stream << n;

	string str = stream.str();

	if (str.length() <= 2)
	{
		cout << 0 << endl;
		return 0;
	}

	for (int i = 0; i < str.length() - 2; ++i)
	{
		stream1 << str[i];
	}
	stream1 << str[str.length() - 1];

	for (int i = 0; i < str.length() - 1; ++i)
	{
		stream2 << str[i];
	}

	int n1, n2;
	stream1 >> n1;
	stream2 >> n2;

	if (n1 > n2)
	{
		cout << n1 << endl;
	}
	else
	{
		cout << n2 << endl;
	}*/

	/*string str;
	cin >> str;

	vector<int> data(str.length() - 1, 0);

	F(data, i)
	{
		if (str[i] == str[i + 1])
		{
			data[i] = 1;
		}
	}

	vector<int> dataInteg(str.length(), 0);

	for (int i = 1; i < dataInteg.size(); ++i)
	{

		dataInteg[i] = data[i - 1] + dataInteg[i - 1];
	}

	int m;
	cin >> m;

	for (int i = 0; i < m;++i)
	{
		int l, r;
		cin >> l >> r;
		l--;
		r--;
		r = min(r, (int)dataInteg.size() - 1);

		cout <<dataInteg[r] - dataInteg[l] << endl;

	}*/

}


#include <iostream>
#include <algorithm>
using namespace std;
long long n[2000001];
int main()
{
	long long m;
	cin >> m;
	for (long long i=0;i<m;i++)
		cin >> n[i];
	sort(n,n+m);
	m--;
	long long count = n[m]+n[m]+n[m-1]+n[m-2]+n[m-3];
	cout << count << endl;
}


#include <iostream>
#include <algorithm>
using namespace std;
long long n[2000001];
int main()
{
	long long m;
	cin >> m;
	for (long long i=0;i<m;i++)
		cin >> n[i];
	sort(n,n+m);
	m--;
	long long count = n[m]+n[m]+n[m-1]+n[m-2]+n[m-3];
	if (m == 0)
		count = n[0];
	cout << count << endl;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <math.h>
using namespace std;
long long n[2000001];
int main()
{
	long long m;
	cin >> m;
	long long count  = 0;
	for (long long i=0;i<m;i++)
	{
		cin >> n[i];
		count += n[i];
	}
	sort(n,n+m);
	if (m==4)
		count += n[m-1];
	long long nn,n2=0;
	long long m2 = m;
	if (m == 1 || m == 4)
	{
		cout << count << endl;
		return 0;
	}
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	//n2++;
	long long v;
	for (long long i=0;i<n2;i++)
	{
		v = pow(4.0,i);
		for (long long j=m-1;j>m-(v+1);j--)
			count += n[j];
	}
	cout << count << endl;
}
	/*long long nn,n2=0;
	long long m2 = m;
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	n2++;
	if (m == 1)
		count = n[0];
	else if (m != 4){
		for (long long i=m-1;i>=0;i--)
		{
			/*if (i == 0)
				nn = n2;
			else{
				nn = n2 - (((i-1) / 4)+1);
			}
			count += n[m-i]*(nn);
		}
		long long v = pow(4.0,(m-1)-i);
		for (long long j=0;j<v;j++)
			count += n[(m-1)-j];
	}
	}
	else count += n[m-1];
	cout << count << endl;
}*/


#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
long long n[2000001];
int main()
{
	long long m;
	cin >> m;
	long long count  = 0;
	for (long long i=0;i<m;i++)
	{
		cin >> n[i];
		count += n[i];
	}
	sort(n,n+m);
	if (m==4)
		count += n[m-1];
	long long nn,n2=0;
	long long m2 = m;
	if (m == 1 || m == 4)
	{
		cout << count << endl;
		return 0;
	}
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	//n2++;
	long long v;
	for (long long i=0;i<n2;i++)
	{
		v = pow(4.0,i);
		for (long long j=m-1;j>m-(v+1);j--)
			count += n[j];
	}
	cout << count << endl;
}
	/*long long nn,n2=0;
	long long m2 = m;
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	n2++;
	if (m == 1)
		count = n[0];
	else if (m != 4){
		for (long long i=m-1;i>=0;i--)
		{
			/*if (i == 0)
				nn = n2;
			else{
				nn = n2 - (((i-1) / 4)+1);
			}
			count += n[m-i]*(nn);
		}
		long long v = pow(4.0,(m-1)-i);
		for (long long j=0;j<v;j++)
			count += n[(m-1)-j];
	}
	}
	else count += n[m-1];
	cout << count << endl;
}*/


#include <iostream>
#include <algorithm>
#include <cmath>
#include <math.h>
using namespace std;
long long n[2000001];
int main()
{
	long long m;
	cin >> m;
	long long count  = 0;
	for (long long i=0;i<m;i++)
	{
		cin >> n[i];
		count += n[i];
	}
	sort(n,n+m);
	if (m==4)
		count += n[m-1];
	long long nn,n2=0;
	long long m2 = m;
	if (m == 1 || m == 4)
	{
		cout << count << endl;
		return 0;
	}
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	//n2++;
	long long v;
	for (long long i=0;i<n2;i++)
	{
		v = pow(4.0,i*1.0);
		for (long long j=m-1;j>m-(v+1);j--)
			count += n[j];
	}
	cout << count << endl;
}
	/*long long nn,n2=0;
	long long m2 = m;
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	n2++;
	if (m == 1)
		count = n[0];
	else if (m != 4){
		for (long long i=m-1;i>=0;i--)
		{
			/*if (i == 0)
				nn = n2;
			else{
				nn = n2 - (((i-1) / 4)+1);
			}
			count += n[m-i]*(nn);
		}
		long long v = pow(4.0,(m-1)-i);
		for (long long j=0;j<v;j++)
			count += n[(m-1)-j];
	}
	}
	else count += n[m-1];
	cout << count << endl;
}*/


#include <iostream>
#include <algorithm>
using namespace std;
long long n[2000001];
int main()
{
	long long m;
	cin >> m;
	long long count  = 0;
	for (long long i=0;i<m;i++)
	{
		cin >> n[i];
		count += n[i];
	}
	sort(n,n+m);
	if (m==4)
		count += n[m-1];
	long long nn,n2=0;
	long long m2 = m;
	if (m == 1 || m == 4)
	{
		cout << count << endl;
		return 0;
	}
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	//n2++;
	long long v;
	for (long long i=0;i<n2;i++)
	{
		v = pow(4.0,i);
		for (long long j=m-1;j>m-(v+1);j--)
			count += n[j];
	}
	cout << count << endl;
}
	/*long long nn,n2=0;
	long long m2 = m;
	while (m2 / 4 > 0)
	{
		m2 /= 4;
		n2++;
	}
	n2++;
	if (m == 1)
		count = n[0];
	else if (m != 4){
		for (long long i=m-1;i>=0;i--)
		{
			/*if (i == 0)
				nn = n2;
			else{
				nn = n2 - (((i-1) / 4)+1);
			}
			count += n[m-i]*(nn);
		}
		long long v = pow(4.0,(m-1)-i);
		for (long long j=0;j<v;j++)
			count += n[(m-1)-j];
	}
	}
	else count += n[m-1];
	cout << count << endl;
}*/


#pragma comment(linker, "/STACK:32777216")
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>

#define LL long long
#define For(i,q1,q2) for(int i=q1;i<=q2;i++)
#define FoR(i,q1,q2) for(int i=q1;i>=q2;i--)
#define mod 1000000007
#define eps 1E-10
#define line 22
#define MP make_pair
#define fs first
#define sc second
#define INF 1LL*2*1000*1000*1000*1000*1000*1000

using namespace std;

void main()
{
    int n;
    cin>>n;
    n--;
    int a[2000000];
    For(i,0,n)
        scanf("%d",&a[i]);
    sort(a,a+n+1);

    LL ans=0;
    int d=1, c=int(log(n+1.0)/log(4.0)+1+eps);
    For(i,0,n)
    {
        ans+=c*a[n-i];
        if (i+1==d) {d*=4; c--;}
    }
    cout<<ans;
}


#pragma comment(linker, "/STACK:32777216")
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>

#define LL long long
#define For(i,q1,q2) for(int i=q1;i<=q2;i++)
#define FoR(i,q1,q2) for(int i=q1;i>=q2;i--)
#define mod 1000000007
#define eps 1E-10
#define line 22
#define MP make_pair
#define fs first
#define sc second
#define INF 1LL*2*1000*1000*1000*1000*1000*1000

using namespace std;

void main()
{
    int n;
    cin>>n;
    n--;
    int a[2000000];
    For(i,0,n)
        scanf("%d",&a[i]);
    sort(a,a+n);

    LL ans=0;
    int d=1, c=int(log(n+1.0)/log(4.0)+1+eps);
    For(i,0,n)
    {
        ans+=c*a[n-i];
        if (i+1==d) {d*=4; c--;}
    }
    cout<<ans;
}


#pragma comment(linker, "/STACK:32777216")
#include <iostream>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <set>
#include <map>
#include <cmath>

#define LL long long
#define For(i,q1,q2) for(int i=q1;i<q2;i++)
#define FoR(i,q1,q2) for(int i=q1-1;i>=q2;i--)
#define mod 1000000007
#define eps 1E-10
#define line 22
#define MP make_pair
#define fs first
#define sc second
#define INF 1LL*2*1000*1000*1000*1000*1000*1000

using namespace std;

void main()
{
    int n;
    cin>>n;
    LL a[2000000];
    For(i,0,n)
        scanf("%d",&a[i]);
    sort(a,a+n);

    LL ans=0;
    LL d=1, c=LL(log(n+1.0)/log(4.0)+1+eps);
    For(i,0,n)
    {
        ans+=c*a[n-i-1];
        if (i+1==d) {d*=4; c--;}
    }
    cout<<ans;
}


#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <cmath>
#include <stdint.h>

using namespace std;

int main( void )
{
	uint32_t n = 0;
	cin >> n;

	vector< uint32_t > v( n );
	for( uint32_t i = 0; i < n; i++ )
	{
		cin >> v[ i ];
	}
	sort( v.begin(), v.end() );
	reverse( v.begin(), v.end() );

	if( n == 1 )
	{
		cout << v[ 0 ];
	}
	else
	{
		uint32_t q = sqrtl( sqrtl( n ) );
		uint32_t k = q + 1;
		uint32_t r = 1;
		uint32_t m = 0;
		for( uint32_t i = 0; i < n; i++ )
		{
			if( i + 1 > r )
			{
				k--;
				r *= 4;
			}
			m += v[ i ] * k;
		}
		cout << m;
	}

	return 0;
}


#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <cmath>
#include <stdint.h>

using namespace std;

int main( void )
{
	uint64_t n = 0;
	cin >> n;

	vector< uint64_t > a( n );
	for( uint64_t i = 0; i < n; i++ )
	{
		cin >> a[ i ];
	}
	sort( a.begin(), a.end() );
	reverse( a.begin(), a.end() );

	if( n == 1 )
	{
		cout << a[ 0 ];
	}
	else
	{
		uint64_t q = 0;
		uint64_t k = 1;
		while( k < n )
		{
			q++;
			k *= 4;
		}
		k = q + 1;

		uint64_t r = 1;
		uint64_t m = 0;
		for( uint64_t i = 0; i < n; i++ )
		{
			if( i + 1 > r )
			{
				k--;
				r *= 4;
			}
			m += a[ i ] * k;
		}
		cout << m;
	}

	return 0;
}


#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <stdint.h>

using namespace std;

int main( void )
{
	uint32_t n = 0;
	cin >> n;

	vector< uint32_t > v( n );
	for( uint32_t i = 0; i < n; i++ )
	{
		cin >> v[ i ];
	}
	sort( v.begin(), v.end() );
	reverse( v.begin(), v.end() );

	if( n == 1 )
	{
		cout << v[ 0 ];
	}
	else
	{
		uint32_t q = sqrt( sqrt( n ) );
		uint32_t k = q + 1;
		uint32_t r = 1;
		uint32_t m = 0;
		for( uint32_t i = 0; i < n; i++ )
		{
			if( i + 1 > r )
			{
				k--;
				r *= 4;
			}
			m += v[ i ] * k;
		}
		cout << m;
	}

	return 0;
}


#include <cstdio>
#include <algorithm>
#include <numeric>

using namespace std;

const int N = 2*1e6 + 100;

long long a[N], n, answer;

int main() {
	scanf("%d", &n);
	for(int i = 0; i < n; i++) scanf("%d", &a[i]);
	sort(a + n - 1, a - 1);
        while (n > 0) {
		answer += accumulate(a, a + n, 0ll);
		n >>= 2;
	}
	printf("%I64d", answer);
}


#include <cstdio>
#include <algorithm>
#include <numeric>

using namespace std;

const int N = 2*1e6 + 100;

long long a[N], n, answer;

int main() {
	scanf("%d", &n);
	for(int i = 0; i < n; i++) scanf("%d", &a[i]);
	sort(a, a + n); reverse(a, a + n);
	while (n > 0) {
		answer += accumulate(a, a + n, 0ll);
		n >>= 2;
	}
	printf("%I64d", answer);
}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
using namespace std;

int a[3000010]={0};
int b[3000010]={0};

int main(){

	int n;
	cin>>n;

	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	if(n==1){
		cout<<a[0]<<endl;
		return 0;
	}
	sort(a,a+n);
	reverse(a,a+n);
	int m=0;
	for(int i=1;i<=n;i*=2){
		if(i==n){
			break;
		}
		m++;
	}
	b[0]=m;
	int f=1;
	int l=1;
	int g=m-1;
	while(1){
		if(g<=0){
			break;
		}
		for(int i=l;i<(l+(f*3));i++){
			b[i]=g;
		}
		l=l+(f*3);
		g-=1;
		f*=4;
	}
	long long ans=0;
	for(int i=0;i<n;i++){
		ans+=(b[i]*a[i]);
	}
	cout<<ans<<endl;

}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
using namespace std;

long long a[3000010]={0};
long long b[3000010]={0};

int main(){

	int n;
	cin>>n;

	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	if(n==1){
		cout<<a[0]<<endl;
		return 0;
	}
	sort(a,a+n);
	reverse(a,a+n);

	int m=0;
	for(int i=1;i<=n;i*=2){
		if(i==n){
			break;
		}
		m++;
	}
	m/=2;

	b[0]=m+1;
	int f=1;
	int l=1;
	int g=m;
	while(1){
		if(g<=0){
			break;
		}
		for(int i=l;i<(l+(f*3));i++){
			b[i]=g;
		}
		l=l+(f*3);
		g-=1;
		f*=4;
	}
	long long ans=0;
	for(int i=0;i<n;i++){
		ans+=(b[i]*a[i]);
	}
	cout<<ans<<endl;

}


#include <iostream>
#include <algorithm>
#include <string>
#include <cmath>
#include <fstream>
#include <iomanip>
using namespace std;

int a[3000010]={0};
int b[3000010]={0};

int main(){

	int n;
	cin>>n;

	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	if(n==1){
		cout<<a[0]<<endl;
		return 0;
	}
	sort(a,a+n);
	reverse(a,a+n);

	int m=0;
	for(int i=1;i<=n;i*=2){
		if(i==n){
			break;
		}
		m++;
	}
	m/=2;

	b[0]=m+1;
	int f=1;
	int l=1;
	int g=m;
	while(1){
		if(g<=0){
			break;
		}
		for(int i=l;i<(l+(f*3));i++){
			b[i]=g;
		}
		l=l+(f*3);
		g-=1;
		f*=4;
	}
	long long ans=0;
	for(int i=0;i<n;i++){
		ans+=(b[i]*a[i]);
	}
	cout<<ans<<endl;

}


#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std ;

int main() {
    int total;
    scanf("%d", &total);
    long * arr = new long[total];

    for (int i = 0; i < total; i++) {
        scanf("%d", arr + i);
    }
    sort(arr, arr + total);

    int temp = total;
    int n = 0;
    while (temp > 1) {
        n++;
        temp /= 4;
    }

    long long res = 0;
    int step = 1;
    int index = total - 1;
    for (int i = n + 1; i >= 1; i--) {
        for (int j = 0; j < step; j++) {
            res += 1L * i * arr[index--];
        }
        step = temp * 3;
        temp *= 4;
    }

    cout << res << endl;

    delete[] arr;
    return 0;
}


#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std ;

int main() {
    int total;
    scanf("%d", &total);
    long long* arr = new long long[total];

    for (int i = 0; i < total; i++) {
        scanf("%d", arr + i);
    }
    sort(arr, arr + total);

    int temp = total;
    int n = 0;
    while (temp > 1) {
        n++;
        temp /= 4;
    }

    long long res = 0;
    int step = 1;
    int index = total - 1;
    for (int i = n + 1; i >= 1; i--) {
        for (int j = 0; j < step; j++) {
            res += 1L * i * arr[index--];
        }
        step = temp * 3;
        temp *= 4;
    }

    cout << res << endl;

    delete[] arr;
    return 0;
}


#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std ;

int main() {
    int total;
    scanf("%d", &total);
    long long * arr = new long long[total];

    for (int i = 0; i < total; i++) {
        //scanf("%lld", arr + i);
        cin >> arr[i];
    }
    sort(arr, arr + total);

    int temp = total;
    int n = 0;
    while (temp > 1) {
        n++;
        temp /= 4;
    }

    long long res = 0;
    int step = 1;
    int index = total - 1;
    for (int i = n + 1; i >= 1; i--) {
        for (int j = 0; j < step; j++) {
            res += 1L * i * arr[index--];
        }
        step = temp * 3;
        temp *= 4;
    }

    cout << res << endl;

    delete[] arr;
    return 0;
}


#include <stdio.h>
#include <stdlib.h>

int *a;
__int64 answer;
int cnt;

int compare(const void *v1, const void *v2)
{
  return *(int*)v2 - *(int*)v1;
}

void ReadData()
{
  scanf("%d", &cnt);
  a = new int[cnt];
  for(int i = 0; i < cnt; i++)
  {
    scanf("%d", &a[i]);
  }
  qsort(a, cnt, sizeof(int), compare);
}

void Solve()
{
  answer = 0;
  int n = -1;
  int copy = cnt;
  while(copy != 0)
  {
    copy >>= 1;
    n++;
  }
  //printf("n:%d\n", n);
  int pos = 0;
  int currentCnt = 1;
  for(int i = 0; i < n; i++)
  {
    for(int j = 0; j < currentCnt; j++)
    {
      answer += (__int64)(n - i) * a[pos];
      pos++;
    }
    currentCnt *= 3;
  }
  if(n == 0)
    answer = a[0];
}

void WriteData()
{
  printf("%I64d\n", answer);
}

int main()
{
  int QWE;
  #ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  scanf("%d", &QWE);
  #else
  QWE = 1;
  #endif
  for(int T = 0; T < QWE; T++)
  {
    ReadData();
    Solve();
    WriteData();
  }
  return 0;
}


#include <stdio.h>
#include <stdlib.h>

__int64 *a;
__int64 answer;
int cnt;

int compare(const void *v1, const void *v2)
{
  return *(__int64*)v2 - *(__int64*)v1;
}

void ReadData()
{
  scanf("%d", &cnt);
  a = new __int64[cnt];
  for(int i = 0; i < cnt; i++)
  {
    scanf("%I64d", &a[i]);
  }
  qsort(a, cnt, sizeof(__int64), compare);
  __int64 sum = 0LL;
  for(int i = 0; i < cnt; i++)
  {
    sum += a[i];
    a[i] = sum;
  }
}

void Solve()
{
  answer = a[0];
  int copy = cnt;
  int n = 0;
  while(copy != 1)
  {
    copy >>= 1;
    n++;
  }
  //printf("n:%d\n", n);
  int current = 4;
  //for(int i = 1; i < n; i++)
  while(current <= cnt)
  {
    answer += a[current - 1];
    current *= 4;
  }
}

void WriteData()
{
  printf("%I64d\n", answer);
}

int main()
{
  if(!1)
  {
    freopen("input.txt", "w", stdout);
    printf("1\n");
    printf("64\n");
    for(int i = 0; i < 64; i++)
    {
      printf("1 ");
    }
    return 0;
  }

  int QWE;
  #ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  scanf("%d", &QWE);
  #else
  QWE = 1;
  #endif
  for(int T = 0; T < QWE; T++)
  {
    ReadData();
    Solve();
    WriteData();
  }
  return 0;
}


#include <stdio.h>
#include <stdlib.h>

__int64 *a;
__int64 answer;
int cnt;

int compare(const void *v1, const void *v2)
{
  return *(__int64*)v2 - *(__int64*)v1;
}

void ReadData()
{
  scanf("%d", &cnt);
  a = new __int64[cnt];
  for(int i = 0; i < cnt; i++)
  {
    scanf("%I64d", &a[i]);
  }
  qsort(a, cnt, sizeof(__int64), compare);
  __int64 sum = 0LL;
  for(int i = 0; i < cnt; i++)
  {
    sum += a[i];
    a[i] = sum;
  }
}

void Solve()
{
  answer = a[0];
  int copy = cnt;
  int n = 0;
  while(copy != 1)
  {
    copy >>= 1;
    n++;
  }
  //printf("n:%d\n", n);
  int current = 4;
  for(int i = 1; i < n; i++)
  {
    answer += a[current - 1];
    current *= 4;
  }
}

void WriteData()
{
  printf("%I64d\n", answer);
}

int main()
{
  int QWE;
  #ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  scanf("%d", &QWE);
  #else
  QWE = 1;
  #endif
  for(int T = 0; T < QWE; T++)
  {
    ReadData();
    Solve();
    WriteData();
  }
  return 0;
}


#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n = 0;
    cin >> n;
    long long int matrix[2000000];
    long long int res[2000000];
    for (int i = 0; i < n; ++i)
        //cin >> matrix[i];
        scanf ("%I64d", &matrix[i]);
    sort(matrix, matrix + n);
    res[0] = matrix[n - 1];
    for (int i = 1; i < n; ++i)
        res[i] = res[i - 1] + matrix[n - i - 1];
    long long int beautiful = 0;
    while (n != 0) {
        beautiful += res[n - 1];
        n /= 4;
    }
    cout << beautiful;
    //::system("pause");
    return 0;
}


#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n = 0;
    cin >> n;
    long long int matrix[2000000];
    long long int res[2000000];
    for (int i = 0; i < n; ++i)
        cin >> matrix[i];
    sort(matrix, matrix + n);
    res[0] = matrix[n - 1];
    for (int i = 1; i < n; ++i)
        res[i] = res[i - 1] + matrix[n - i - 1];
    long long int beautiful = 0;
    while (n != 0) {
        beautiful += res[n - 1];
        n /= 4;
    }
    cout << beautiful;
    //::system("pause");
    return 0;
}


#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n = 0;
    cin >> n;
    vector<long long int> matrix(n);
    vector<long long int> res(n, 0);
    for (int i = 0; i < n; ++i)
        cin >> matrix[i];
    sort(matrix.begin(), matrix.end());
    res[0] = matrix[n - 1];
    for (int i = 1; i < n; ++i)
        res[i] = res[i - 1] + matrix[n - i - 1];
    long long int beautiful = 0;
    while (n != 0) {
        beautiful += res[n - 1];
        n /= 4;
    }
    cout << beautiful;
    //::system("pause");
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    cin>>n;
    vector<int> vec;
    for(int i=0;i<n;i++)
    {
        int k;cin>>k;
        vec.push_back(k);
    }
    sort(vec.begin(),vec.end());
    reverse(vec.begin(), vec.end());
    int idx = 1;
    int sum=0;
    do
    {
        for(int i=0; i<idx; i++)
            sum+=vec[i];
        idx*=4;
    }
    while(idx<= vec.size());
    cout << sum;
    return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> vec;

int calculate(int ch, int l,int r)
{
    if (l==r)
        return ch;
    else if (r-l+2 == 4){
        return ch + vec[l] + vec[l+1] + vec[l+2];
    }
    else if(r-l+1 ==4)
    {
        return vec[l] + vec[l] + vec[l+1] + vec[l+2] + vec[l+3];
    }
    else{
        int sum = 0;
        for(int i=0; i<4; i++){
            sum+=vec[i];
            sum += calculate(vec[i], 4+(4*i)-i, 6+(4*i)-i);
        }
        return sum;
    }
}

int main()
{
    freopen("input.txt", "r", stdin);

    int k;cin>>k;

    for(int i=0; i<k; i++)
    {
        int k;
        cin>>k;
        vec.push_back(k);
    }
    sort(vec.begin(), vec.end());
    reverse(vec.begin(),vec.end());
    long sum = 0;
    int i = 1;
    sum += calculate(vec[0], 0, vec.size()-1);
    if (k > 4)
        sum+=vec[0];

    cout << sum;
    return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    cin>>n;
    vector<int> vec;
    for(int i=0;i<n;i++)
    {
        int k;cin>>k;
        vec.push_back(k);
    }
    sort(vec.begin(),vec.end());
    reverse(vec.begin(), vec.end());
    int idx = 1;
    long long sum=0;
    do
    {
        for(int i=0; i<idx; i++)
            sum+=vec[i];
        idx*=4;
    }
    while(idx<= vec.size());
    cout << sum;
    return 0;
}


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
b = {}
for ai in a:
    b[ai] = []
amt = 0
for i in xrange(1, len(a)):
    amt += abs(a[i] - a[i-1])
    if a[i] - a[i-1]:
        b[a[i]] += [a[i-1]]
        b[a[i-1]] += [a[i]]
diff = 0
for bi in b:
    if b[bi]:
        center = sorted(b[bi])[len(b[bi])/2]
        sum = 0
        for page in b[bi]:
            sum += abs(page - center) - abs(page - bi)
        diff = min(diff, sum)
print amt + diff


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

maxx = 0
fuck = []
for i in lis.keys():
    l = len(lis[i])
    org = 0
    for x in lis[i]:
        org += abs (i-x)
    ri = 0
    le = l - 1
    new = 0
    lis[i].sort(cmp=None, key=None, reverse=False)
    while (ri < le):
        new += abs (lis[i][ri] - lis[i][le])
        ri += 1
        le -= 1
    maxx = max (maxx, org - new)
print summ - maxx


#-*- encoding: utf-8 -*-

'''
Created on 2014��5��30��

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for hh in a:
    lis[hh] = []

for i in xrange (m-1):
    summ += abs(a[i+1] - a[i])
    if a[i] != a[i - 1]:
        lis[a[i]].append (a[i+1])
        lis[a[i+1]].append (a[i])

maxx = 0
fuck = []
for i in lis.keys():
    l = len(lis[i])
    org = 0
    for x in lis[i]:
        org += abs (i-x)
    ri = 0
    le = l - 1
    new = 0
    lis[i].sort(cmp=None, key=None, reverse=False)
    while (ri < le):
        new += abs (lis[i][ri] - lis[i][le])
        ri += 1
        le -= 1
    maxx = max (maxx, org - new)
print summ - maxx


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])

    summ += abs(a[i+1] - a[i])

#print lis
fuck = []
for i in lis.keys():
    tmp = 0
    for j in lis[i]:
        tmp += abs(i-j)
    for j in lis[i]:
        tmpp = 0
        for k in lis[i]:
            if k != i:
                tmpp += abs(j-k)
        fuck.append(tmp - tmpp)
print summ - max(fuck)

print lis
print fuck


#-*- encoding: utf-8 -*-

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

maxx = 0
fuck = []
for i in lis.keys():
    lis[i].sort()
    mid = lis[i][len(lis[i])/2]
    ch = 0
    for p in lis[i]:
        ch += abs(p - i) - abs(p - mid)
    maxx = max(maxx, ch)
print summ - maxx


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

fuck = []
for i in lis.keys():
    l = len(lis[i])
    org = 0
    for x in lis[i]:
        org += abs (i-x)
    ri = 0
    le = l - 1
    new = 0
    lis[i].sort(cmp=None, key=None, reverse=False)
    while (ri < le):
        new += abs (lis[i][ri] - lis[i][le])
        ri += 1
        le -= 1
    fuck.append(org - new)
print summ - max(fuck)


#-*- encoding: utf-8 -*-

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for hh in a:
    lis[hh] = []

for i in xrange (m-1):
    summ += abs(a[i+1] - a[i])
    if a[i] != a[i - 1]:
        lis[a[i]].append (a[i+1])
        lis[a[i+1]].append (a[i])

maxx = 0
fuck = []
for i in lis.keys():
    if lis[i]:
        lis[i].sort()
        mid = lis[i][len(lis[i])/2]
        ch = 0
        for p in lis[i]:
            ch += abs(p - i) - abs(p - mid)
        maxx = max(maxx, ch)

print summ - maxx


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []
    if a[i] != a[i+1]:
        lis[a[i]].append (a[i+1])
        lis[a[i+1]].append (a[i])

    summ += abs(a[i+1] - a[i])

#print lis
fuck = []
for i in lis.keys():
    tmp = 0
    for j in lis[i]:
        tmp += abs(i-j)
    for j in lis[i]:
        tmpp = 0
        for k in lis[i]:
            tmpp += abs(j-k)
        fuck.append(tmp - tmpp)
print summ - max(fuck)

'''
summ = abs(a[1]-a[0])
fuck = []
tmp = abs(a[1] - a[0])
for k in xrange ( 0+1, m-1 ):
        if a[k] == a[0]:
            tmp += abs(a[k]-a[k-1]) + abs(a[k+1] - a[k]) - \
            (abs(a[1]-a[k-1]) + abs(a[k+1] - a[1])) \

if a[m-1] == a [0]:
    tmp += (abs(a[m-1]-a[m-2]) - abs(a[1] - a[m-2]))
fuck.append(tmp)

for j in xrange( 1, m-1 ):
    summ += abs(a[j+1] - a[j])
    tmp = abs(a[j]-a[j-1]) + abs(a[j+1] - a[j]) - abs(a[j+1] - a[j-1])
    for k in xrange ( 1, m-1 ) :
        if a[k] == a[j] and k != j:
            tmp += abs(a[k]-a[k-1]) + abs(a[k+1] - a[k]) - \
            min( (abs(a[j-1]-a[k-1]) + abs(a[k+1] - a[j-1])), \
                 (abs(a[j+1]-a[k-1]) + abs(a[k+1] - a[j+1])) )
    fuck.append(tmp)

tmp = abs(a[m-1] - a[m-2])

for k in xrange ( 1, m-1 ):
        if a[k] == a[m-1]:
            tmp += abs(a[k]-a[k-1]) + abs(a[k+1] - a[k]) - \
            (abs(a[m-2]-a[k-1]) + abs(a[k+1] - a[m-2])) \

if a[m-1] == a [0]:
    tmp -= (abs(a[m-1]-a[m-2]) - abs(a[1] - a[m-2]))
fuck.append(tmp)

print summ - max (fuck)

'''


#-*- encoding: utf-8 -*-

'''
Created on 2014��5��30��

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for hh in a:
    lis[hh] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

maxx = 0
fuck = []
for i in lis.keys():
    l = len(lis[i])
    org = 0
    for x in lis[i]:
        org += abs (i-x)
    ri = 0
    le = l - 1
    new = 0
    lis[i].sort(cmp=None, key=None, reverse=False)
    while (ri < le):
        new += abs (lis[i][ri] - lis[i][le])
        ri += 1
        le -= 1
    maxx = max (maxx, org - new)
print summ - maxx


n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

maxx = 0
fuck = []
for i in lis.keys():
    lis[i].sort()
    mid = lis[i][len(lis[i])/2]
    ch = 0
    for p in lis[i]:
        ch += abs(p - i) - abs(p - mid)
    maxx = max(maxx, ch)

print summ - maxx


#-*- encoding: utf-8 -*-

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for hh in a:
    lis[hh] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

maxx = 0
fuck = []
for i in lis.keys():
    lis[i].sort()
    mid = lis[i][len(lis[i])/2]
    ch = 0
    for p in lis[i]:
        ch += abs(p - i) - abs(p - mid)
    maxx = max(maxx, ch)

print summ - maxx


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

fuck = []
for i in lis.keys():
    tmp = 0
    for j in lis[i]:
        tmp += abs(i-j)
    for j in lis[i]:
        tmpp = 0
        for k in lis[i]:
            if k != i:
                tmpp += abs(j-k)
        fuck.append(tmp - tmpp)
print summ - max(fuck)


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])

    summ += abs(a[i+1] - a[i])

#print lis
fuck = []
for i in lis.keys():
    tmp = 0
    for j in lis[i]:
        tmp += abs(i-j)
    for j in lis[i]:
        tmpp = 0
        for k in lis[i]:
            if k != i:
                tmpp += abs(j-k)
        fuck.append(tmp - tmpp)
print summ - max(fuck)


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
#    print 'i=', i
    lis[a[i]].append (a[i+1])
#    print a[i]
    lis[a[i+1]].append (a[i])
#    print a[i+1]
    summ += abs(a[i+1] - a[i])

#print lis
fuck = []
for i in lis.keys():
    tmp = 0
    for j in lis[i]:
        tmp += abs(i-j)
    for j in lis[i]:
        tmpp = 0
        for k in lis[i]:
            if k != i:
                tmpp += abs(j-k)
        fuck.append(tmp - tmpp)
print summ - max(fuck)

#print summ
#print fuck
#print lis


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

summ = abs(a[1]-a[0])

fuck = [abs(a[1] - a[0])]

for j in xrange( 1, m-1 ):
    summ += abs(a[j+1] - a[j])
    fuck.append( abs(a[j]-a[j-1]) + abs(a[j+1] - a[j]) - abs(a[j+1] - a[j-1]) )

fuck.append(abs(a[m-1]-a[m-2]))

print summ - max(fuck)

'''
def tryy (i, j):
    b = []
    for k in a:
        if k != i:
            b.append( k )
        else:
            b.append( j )
    summ = 0
    for i in xrange( m-1 ):
        summ += abs(b[i+1]-b[i])
    return summ

'''


#-*- encoding: utf-8 -*-

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

for i in xrange (m-1):
    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])
    summ += abs(a[i+1] - a[i])

maxx = 0
fuck = []
for i in lis.keys():
    lis[i].sort()
    mid = lis[i][len(lis[i])/2]
    ch = 0
    for p in lis[i]:
        ch += abs(p - i) - abs(p - mid)
    maxx = max(maxx, ch)

print summ - maxx


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

exi = [a[0]]

for i in xrange( m-1 ):
    if exi.count(a[i+1]) == 0:
        exi.append( a[i+1] )

def tryy (i, j):
    b = []
    for k in a:
        if k != i:
            b.append( k )
        else:
            b.append( j )
    summ = 0
    for i in xrange( m-1 ):
        summ += abs(b[i+1]-b[i])
    return summ

minn = tryy (exi[0], exi[1])
for i in exi:
    for j in exi:
        if tryy (i, j) < minn:
            minn = tryy (i, j)

print minn


#-*- encoding: utf-8 -*-

'''
Created on 2014年5月30日

@author: LachrY
'''

n, m = map( int, raw_input().split() )
a = map( int, raw_input().split() )

lis = {}
summ = 0

for i in xrange (m-1):
    if a[i] not in lis.keys() or a[i+1] not in lis.keys():
        lis[a[i]] = []
        lis[a[i+1]] = []

    lis[a[i]].append (a[i+1])
    lis[a[i+1]].append (a[i])

    summ += abs(a[i+1] - a[i])

#print lis
fuck = []
for i in lis.keys():
    tmp = 0
    for j in lis[i]:
        tmp += abs(i-j)
    for j in lis[i]:
        tmpp = 0
        for k in lis[i]:
            tmpp += abs(j-k)
        fuck.append(tmp - tmpp)
print summ - max(fuck)


r=raw_input;r()
L=map(list,7**6*[[]])
a=map(int,r().split())
for i,j in zip(a,a[1:]):
	if i!=j:L[i]+=[j];L[j]+=[i]
z=b=0
Q=lambda l,i:sum(abs(i-v)for v in l)
for i,l in enumerate(L):
	if l:t=Q(l,i);z+=t;b=min(b,Q(l,sorted(l)[len(l)/2])-t)
print z/2+b


def main():
	n, m = map(int, raw_input().split())
	a = map(int, raw_input().split())
	total = [[] for i in xrange(n + 1)]
	for i in xrange(m):
		if i > 0: total[a[i]].append(a[i - 1])
		if i < m - 1: total[a[i]].append(a[i + 1])
	f, t, maxDec = 1, 1, -1
	for i in xrange(1, n + 1):
		if not total[i]: continue
		sn = len(total[i])
		left, right, j = 1, n, i
		while left <= right:
			mid = (left + right) >> 1
			sx = 0
			for x in total[i]:
				if x <= mid: sx += 1
			if 2 * sx >= sn:
				j = mid
				right = mid - 1
			else: left = mid + 1
		tmp = sum([abs(x - i) for x in total[i]]) - sum([abs(x - j) for x in total[i]])
#		print i, j, tmp
		if tmp > maxDec: maxDec, f, t = tmp, i, j
#	print f, t
	for i in xrange(m):
		if a[i] == f: a[i] = t
	print sum([abs(a[i + 1] - a[i]) for i in xrange(m - 1)])

if __name__ == "__main__": main()


def main():
	n, m = map(int, raw_input().split())
	a = map(int, raw_input().split())
	total = [[] for i in xrange(n + 1)]
	s = 0
	for i in xrange(1, m):
		if a[i] != a[i - 1]:
			s += abs(a[i] - a[i - 1])
			total[a[i]].append(a[i - 1])
			total[a[i - 1]].append(a[i])
	maxDec = -1
	for i in xrange(1, n + 1):
		if not total[i]: continue
		s1 = sum([abs(i - x) for x in total[i]])
		left, right = 0, len(total[i]) - 1
		s2 = 0
		total[i].sort()
		while left < right:
			s2 += total[i][right] - total[i][left]
			left += 1
			right -= 1
		maxDec = max(maxDec, s1 - s2)
	print s - maxDec

if __name__ == "__main__": main()


def main():
	n, m = map(int, raw_input().split())
	a = map(int, raw_input().split())
	total = [[] for i in xrange(n + 1)]
	for i in xrange(m):
		if i > 0 and a[i - 1] != a[i]: total[a[i]].append(a[i - 1])
		if i < m - 1 and a[i + 1] != a[i]: total[a[i]].append(a[i + 1])
	f, t, maxDec = 1, 1, -1
	for i in xrange(1, n + 1):
		if not total[i]: continue
		sn = len(total[i])
		left, right, j = 1, n, i
		while left <= right:
			mid = (left + right) >> 1
			sx = 0
			for x in total[i]:
				if x <= mid: sx += 1
			if 2 * sx >= sn:
				j = mid
				right = mid - 1
			else: left = mid + 1
		tmp = sum([abs(x - i) for x in total[i]]) - sum([abs(x - j) for x in total[i]])
#		print i, j, tmp
		if tmp > maxDec: maxDec, f, t = tmp, i, j
#	print f, t
	for i in xrange(m):
		if a[i] == f: a[i] = t
	print sum([abs(a[i + 1] - a[i]) for i in xrange(m - 1)])

if __name__ == "__main__": main()


def main():
	n, m = map(int, raw_input().split())
	a = map(int, raw_input().split())
	total = [[] for i in xrange(n + 1)]
	s = 0
	for i in xrange(1, m):
		if a[i] != a[i - 1]:
			s += abs(a[i] - a[i - 1])
			total[a[i]].append(a[i - 1])
			total[a[i - 1]].append(a[i])
	maxDec = 0
	for i in xrange(1, n + 1):
		if not total[i]: continue
		s1 = sum([abs(i - x) for x in total[i]])
		left, right = 0, len(total[i]) - 1
		s2 = 0
		total[i].sort()
		while left < right:
			s2 += total[i][right] - total[i][left]
			left += 1
			right -= 1
		maxDec = max(maxDec, s1 - s2)
	print s - maxDec

if __name__ == "__main__": main()


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{

    class Program
    {
        public static readonly int MOD = Convert.ToInt32(1e9 + 7);
        public static readonly int oo = Convert.ToInt32(1e9);
        public static readonly long OO = Convert.ToInt64(1e18);

        static void Main(string[] args)
        {
            String[] data = Console.ReadLine().Split(' ');
            n = int.Parse(data[0]);
            m = int.Parse(data[1]);
            a = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            if (m == 1)
            {
                Console.Write(0);
                return;
            }
            b = new int[m];
            Array.Copy(a, b, m);
            Array.Sort(b);

            diff = new long[m + 1];
            for (int i = 1; i < m; i++)
            {
                diff[i] = Math.Abs(a[i] - a[i - 1]) + diff[i - 1];
            }

            long ans = diff[m - 1];

            for (int i = 0; i < m; i++)
            {
                if (i == 0)
                {
                    ans = Utils.Min(ans, diff[m - 1] - diff[i + 1]);
                } else if (i == m - 1)
                {
                    ans = Utils.Min(ans, diff[i - 1]);
                } else
                {
                    int min = Math.Min(a[i - 1], a[i + 1]);
                    int max = Math.Max(a[i - 1], a[i + 1]);
                    ans = Math.Min(ans, max - min + diff[i - 1] + diff[m - 1] - diff[i + 1]);

                    int can = Utils.LowerBound(b, 0, m, min);
                    if (can < m && b[can] <= max)
                    {
                        ans = Math.Min(ans, max - min + diff[i - 1] + diff[m - 1] - diff[i + 1]);
                    }
                }
            }
            Console.Write(ans);
        }

        private static int n, m;
        private static int[] a, b;
        private static long[] diff;

        public static int Small(int x)
        {
            return x - b[0];
        }

        public static int Big(int x)
        {
            return b[m - 1] - x;
        }

    }

    static class Utils
    {
        public static int LowerBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static int UpperBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] > k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static long Max(params long[] a)
        {
            return a.Max();
        }

        public static long Min(params long[] a)
        {
            return a.Min();
        }

    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{

    class Program
    {
        public static readonly int MOD = Convert.ToInt32(1e9 + 7);
        public static readonly int oo = Convert.ToInt32(1e9);
        public static readonly long OO = Convert.ToInt64(1e18);

        static void Main(string[] args)
        {
            String[] data = Console.ReadLine().Split(' ');
            int n = int.Parse(data[0]);
            int m = int.Parse(data[1]);
            int[] a = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            if (m == 1)
            {
                Console.Write(0);
                return;
            }
            List<int>[] map = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
            {
                map[i] = new List<int>();
            }
            if (a[1] != a[0]) map[a[0]].Add(a[1]);
            if (a[m - 1] != a[m - 2]) map[a[m - 1]].Add(a[m - 2]);
            for (int i = 1; i < m - 1; i++)
            {
                if (a[i - 1] != a[i]) map[a[i]].Add(a[i - 1]);
                if (a[i + 1] != a[i]) map[a[i]].Add(a[i + 1]);
            }

            long diff = 0;
            for (int i = 1; i < m;  i++)
            {
                diff += Math.Abs(a[i] - a[i - 1]);
            }
            long ans = diff;
            for (int i = 1; i <= n; i++)
            {
                int size = map[i].Count;
                if (size == 0) continue;
                map[i].Sort();
                long[] sum = new long[size + 1];
                for (int j = 1; j <= size; j++)
                {
                    sum[j] = sum[j - 1] + map[i][j - 1];
                }
                long res = diff;
                int median = map[i][size / 2];
                foreach (int x in map[i])
                {
                    res += Math.Abs(x - median) - Math.Abs(x - i);
                }

                ans = Math.Min(ans, res);
            }
            Console.Write(ans);

        }

    }

    static class Utils
    {
        public static int LowerBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static int UpperBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] > k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static long Max(params long[] a)
        {
            return a.Max();
        }

        public static long Min(params long[] a)
        {
            return a.Min();
        }

    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{

    class Program
    {
        public static readonly int MOD = Convert.ToInt32(1e9 + 7);
        public static readonly int oo = Convert.ToInt32(1e9);
        public static readonly long OO = Convert.ToInt64(1e18);

        static void Main(string[] args)
        {
            String[] data = Console.ReadLine().Split(' ');
            int n = int.Parse(data[0]);
            int m = int.Parse(data[1]);
            int[] a = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            if (m == 1)
            {
                Console.Write(0);
                return;
            }
            List<int>[] map = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
            {
                map[i] = new List<int>();
            }
            if (a[1] != a[0]) map[a[0]].Add(a[1]);
            if (a[m - 1] != a[m - 2]) map[a[m - 1]].Add(a[m - 2]);
            for (int i = 1; i < m - 1; i++)
            {
                if (a[i - 1] != a[i]) map[a[i]].Add(a[i - 1]);
                if (a[i + 1] != a[i]) map[a[i]].Add(a[i + 1]);
            }

            int[] b = a.Distinct().OrderBy(x => x).ToArray();

            long diff = 0;
            for (int i = 1; i < m;  i++)
            {
                diff += Math.Abs(a[i] - a[i - 1]);
            }
            long ans = diff;
            for (int i = 1; i <= n; i++)
            {
                int size = map[i].Count;
                if (size == 0) continue;
                map[i].Sort();
                long[] sum = new long[size + 1];
                for (int j = 1; j <= size; j++)
                {
                    sum[j] = sum[j - 1] + map[i][j - 1];
                }
                long res = diff;
                int median = map[i][size / 2];
                foreach (int x in map[i])
                {
                    res += Math.Abs(x - median) - Math.Abs(x - i);
                }

                ans = Math.Min(ans, res);
            }
            Console.Write(ans);

        }

    }

    static class Utils
    {
        public static int LowerBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static int UpperBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] > k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static long Max(params long[] a)
        {
            return a.Max();
        }

        public static long Min(params long[] a)
        {
            return a.Min();
        }

    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Codeforces
{

    class Program
    {
        public static readonly int MOD = Convert.ToInt32(1e9 + 7);
        public static readonly int oo = Convert.ToInt32(1e9);
        public static readonly long OO = Convert.ToInt64(1e18);

        static void Main(string[] args)
        {
            String[] data = Console.ReadLine().Split(' ');
            int n = int.Parse(data[0]);
            int m = int.Parse(data[1]);
            int[] a = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();
            if (m == 1)
            {
                Console.Write(0);
                return;
            }
            List<int>[] map = new List<int>[n + 1];
            for (int i = 1; i <= n; i++)
            {
                map[i] = new List<int>();
            }
            if (a[1] != a[0]) map[a[0]].Add(a[1]);
            if (a[m - 1] != a[m - 2]) map[a[m - 1]].Add(a[m - 2]);
            for (int i = 1; i < m - 1; i++)
            {
                if (a[i - 1] != a[i]) map[a[i]].Add(a[i - 1]);
                if (a[i + 1] != a[i]) map[a[i]].Add(a[i + 1]);
            }

            long diff = 0;
            for (int i = 1; i < m;  i++)
            {
                diff += Math.Abs(a[i] - a[i - 1]);
            }
            long ans = diff;
            for (int i = 1; i <= n; i++)
            {
                int size = map[i].Count;
                if (size == 0) continue;
                map[i].Sort();
                long res = diff;
                int median = map[i][size / 2];
                foreach (int x in map[i])
                {
                    res += Math.Abs(x - median) - Math.Abs(x - i);
                }

                ans = Math.Min(ans, res);
            }
            Console.Write(ans);

        }

    }

    static class Utils
    {
        public static int LowerBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] >= k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static int UpperBound(int[] a, int l, int r, int k)
        {
            int m = 0, ans = r;
            while (l < r) if (a[m = l + r >> 1] > k) ans = r = m; else l = m + 1;
            return ans;
        }

        public static long Max(params long[] a)
        {
            return a.Max();
        }

        public static long Min(params long[] a)
        {
            return a.Min();
        }

    }

}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Globalization;

namespace _433c_
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        private static Dictionary<int, int>[] g;

        private static void Add(int prev, int next)
        {
            var dic = g[prev];
            if (dic == null)
            {
                dic = new Dictionary<int, int>();
                g[prev] = dic;
            }

            if (!dic.ContainsKey(next))
            {
                dic[next] = 0;
            }

            dic[next]++;
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();
            g = new Dictionary<int, int>[n + 1];
            var prev = a[0];
            for (int i = 1; i < m; i++)
            {
                var next = a[i];
                if (next == prev)
                {
                    continue;
                }

                Add(prev, next);
                Add(next, prev);

                prev = next;
            }

            var distN = a.Distinct().Count();
            var map = new int[distN];
            var dmap = new List<Tuple<int, int>>[distN];
            var ind = 0;
            var acc = new int[n + 1];
            for (int i = 0; i < m; i++)
            {
                var next = a[i];
                acc[next]++;
                if (acc[next] == 1)
                {
                    map[ind] = next;
                    dmap[ind] = g[next].Select(v => Tuple.Create(v.Key, v.Value)).OrderBy(t => t.Item1).ToList();
                    ind++;
                }
            }

            Array.Sort(map, dmap);

            var minFrom = -1;
            var minTo = -1;
            var maxVal = long.MinValue;
            for (int i = 0; i < distN; i++)
            {
                var next = map[i];
                var dic = dmap[i];

                var totalSum = dic.Sum(v => (long)v.Item2);
                var half = totalSum / 2 + totalSum % 2;

                var locSum = 0L;
                var pinTo = -1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    var nextLocSum = locSum + val.Item2;
                    if (nextLocSum == half || (nextLocSum > half && locSum < half))
                    {
                        pinTo = j;
                        break;
                    }

                    locSum = nextLocSum;
                }

                var curSum = 0L;
                var newSum = 0L;
                var newPos = dic[pinTo].Item1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    curSum += Math.Abs(next - val.Item1) * (long)val.Item2;
                    newSum += Math.Abs(newPos - val.Item1) * (long)val.Item2;
                }

                var locMax = curSum - newSum;
                if (locMax <= 0)
                {
                    continue;
                }

                if (locMax > maxVal)
                {
                    maxVal = locMax;
                    minFrom = next;
                    minTo = newPos;
                }
            }

            var result = 0L;
            var prevM = a[0];
            if (prevM == minFrom)
            {
                prevM = minTo;
            }

            for (int i = 1; i < m; i++)
            {
                var nextM = a[i];
                if (nextM == minFrom)
                {
                    nextM = minTo;
                }

                result += Math.Abs(prevM - nextM);
                prevM = nextM;
            }

            Console.WriteLine(result);
            //var cs = new int[m];
            //for (int i = 0; i < m; i++)
            //{
            //    cs[i] = counts[a[i]];
            //}

            //Array.Sort(a, cs);

            //var total = cs.Sum();
            //var half = total / 2;
            //var seekHalf = half + total % 2;
            //var left = 0;

            //for (int i = 0; i < m; i++)
            //{
            //    var nextL = left + cs[i];
            //    if (nextL == seekHalf)
            //    {

            //    }
            //}
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Globalization;

namespace _433c_
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        private static Dictionary<int, int>[] g;

        private static void Add(int prev, int next)
        {
            var dic = g[prev];
            if (dic == null)
            {
                dic = new Dictionary<int, int>();
                g[prev] = dic;
            }

            if (!dic.ContainsKey(next))
            {
                dic[next] = 0;
            }

            dic[next]++;
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();
            g = new Dictionary<int, int>[n + 1];
            var prev = a[0];
            for (int i = 1; i < m; i++)
            {
                var next = a[i];
                if (next == prev)
                {
                    continue;
                }

                Add(prev, next);
                Add(next, prev);

                prev = next;
            }

            var distN = a.Distinct().Count();
            var map = new int[distN];
            var dmap = new List<Tuple<int, int>>[distN];
            var ind = 0;
            var acc = new int[n + 1];
            for (int i = 0; i < m; i++)
            {
                var next = a[i];
                acc[next]++;
                if (acc[next] == 1)
                {
                    map[ind] = next;
                    dmap[ind] = g[next].Select(v => Tuple.Create(v.Key, v.Value)).OrderBy(t => t.Item1).ToList();
                    ind++;
                }
            }

            Array.Sort(map, dmap);

            var minFrom = -1;
            var minTo = -1;
            var maxVal = long.MinValue;
            for (int i = 0; i < distN; i++)
            {
                var next = map[i];
                var dic = dmap[i];

                var totalSum = dic.Sum(v => (long)v.Item2);
                var half = totalSum / 2 + totalSum % 2;

                var locSum = 0L;
                var pinTo = -1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    var nextLocSum = locSum + val.Item2;
                    if (nextLocSum == half || (nextLocSum > half && locSum < half))
                    {
                        pinTo = j;
                        break;
                    }
                }

                var curSum = 0L;
                var newSum = 0L;
                var newPos = dic[pinTo].Item1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    curSum += Math.Abs(next - val.Item1) * (long)val.Item2;
                    newSum += Math.Abs(newPos - val.Item1) * (long)val.Item2;
                }

                var locMax = curSum - newSum;
                if (locMax <= 0)
                {
                    continue;
                }

                if (locMax > maxVal)
                {
                    maxVal = locMax;
                    minFrom = next;
                    minTo = newPos;
                }
            }

            var result = 0L;
            var prevM = a[0];
            if (prevM == minFrom)
            {
                prevM = minTo;
            }

            for (int i = 1; i < m; i++)
            {
                var nextM = a[i];
                if (nextM == minFrom)
                {
                    nextM = minTo;
                }

                result += Math.Abs(prevM - nextM);
                prevM = nextM;
            }

            Console.WriteLine(result);
            //var cs = new int[m];
            //for (int i = 0; i < m; i++)
            //{
            //    cs[i] = counts[a[i]];
            //}

            //Array.Sort(a, cs);

            //var total = cs.Sum();
            //var half = total / 2;
            //var seekHalf = half + total % 2;
            //var left = 0;

            //for (int i = 0; i < m; i++)
            //{
            //    var nextL = left + cs[i];
            //    if (nextL == seekHalf)
            //    {

            //    }
            //}
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Globalization;

namespace _433c_
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        private static Dictionary<int, int>[] g;

        private static void Add(int prev, int next)
        {
            var dic = g[prev];
            if (dic == null)
            {
                dic = new Dictionary<int, int>();
                g[prev] = dic;
            }

            if (!dic.ContainsKey(next))
            {
                dic[next] = 0;
            }

            dic[next]++;
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();
            var counts = new int[n + 1];
            g = new Dictionary<int, int>[n + 1];
            var prev = a[0];
            for (int i = 1; i < m; i++)
            {
                var next = a[i];
                if (next == prev)
                {
                    continue;
                }

                Add(prev, next);
                Add(next, prev);

                counts[prev]++;
                counts[next]++;
                prev = next;
            }
            var distN = a.Distinct().Count();
            var map = new int[distN];
            var dmap = new List<Tuple<int, int>>[distN];
            var ind = 0;
            var acc = new int[n + 1];
            for (int i = 0; i < m; i++)
            {
                var next = a[i];
                acc[next]++;
                if (acc[next] == 1)
                {
                    map[ind] = next;
                    dmap[ind] = g[next].Select(v => Tuple.Create(v.Key, v.Value)).OrderBy(t => t.Item1).ToList();
                    ind++;
                }
            }

            Array.Sort(map, dmap);
            var total = dmap.Sum(d1 => d1.Count);
            var totalSums = dmap.Select(d1 => d1.Sum(d2 => d2.Item2)).ToArray();

            var minFrom = -1;
            var minTo = -1;
            var maxVal = long.MinValue;
            for (int i = 0; i < distN; i++)
            {
                var next = map[i];
                var dic = dmap[i];

                var totalSum = dic.Sum(v => v.Item2);
                var half = totalSum / 2 + totalSum % 2;

                var locSum = 0;
                var pinTo = -1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    var nextLocSum = locSum + val.Item2;
                    if (nextLocSum == half || (nextLocSum > half && locSum < half))
                    {
                        pinTo = j;
                        break;
                    }
                }

                var curSum = 0L;
                var newSum = 0L;
                var newPos = dic[pinTo].Item1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    curSum += Math.Abs(next - val.Item1) * val.Item2;
                    newSum += Math.Abs(newPos - val.Item1) * val.Item2;
                }

                var locMax = curSum - newSum;
                if (locMax <= 0)
                {
                    continue;
                }

                if (locMax > maxVal)
                {
                    maxVal = locMax;
                    minFrom = next;
                    minTo = newPos;
                }
            }

            var result = 0L;
            var prevM = a[0];
            if (prevM == minFrom)
            {
                prevM = minTo;
            }

            for (int i = 1; i < m; i++)
            {
                var nextM = a[i];
                if (nextM == minFrom)
                {
                    nextM = minTo;
                }

                result += Math.Abs(prevM - nextM);
                prevM = nextM;
            }

            Console.WriteLine(result);
            //var cs = new int[m];
            //for (int i = 0; i < m; i++)
            //{
            //    cs[i] = counts[a[i]];
            //}

            //Array.Sort(a, cs);

            //var total = cs.Sum();
            //var half = total / 2;
            //var seekHalf = half + total % 2;
            //var left = 0;

            //for (int i = 0; i < m; i++)
            //{
            //    var nextL = left + cs[i];
            //    if (nextL == seekHalf)
            //    {

            //    }
            //}
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


#if DEBUG
using System.Reflection;
using System.Threading.Tasks;
#endif

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Globalization;

namespace _433c_
{
    class Program
    {
        static string _inputFilename = "input.txt";
        static string _outputFilename = "output.txt";
        static bool _useFileInput = false;

        static void Main(string[] args)
        {
            StreamWriter file = null;
#if DEBUG
			Console.SetIn(getInput());
#else
            if (_useFileInput)
            {
                Console.SetIn(File.OpenText(_inputFilename));
                file = new StreamWriter(_outputFilename);
                Console.SetOut(file);
            }
#endif

            try
            {
                solution();
            }
            finally
            {
                if (_useFileInput)
                {
                    file.Close();
                }
            }
        }

        private static Dictionary<int, int>[] g;

        private static void Add(int prev, int next)
        {
            var dic = g[prev];
            if (dic == null)
            {
                dic = new Dictionary<int, int>();
                g[prev] = dic;
            }

            if (!dic.ContainsKey(next))
            {
                dic[next] = 0;
            }

            dic[next]++;
        }

        static void solution()
        {
            #region SOLUTION
            var d = readIntArray();
            var n = d[0];
            var m = d[1];
            var a = readIntArray();
            g = new Dictionary<int, int>[n + 1];
            var prev = a[0];
            var count = 0;
            for (int i = 1; i < m; i++)
            {
                var next = a[i];
                if (next == prev)
                {
                    continue;
                }

                Add(prev, next);
                Add(next, prev);
                count++;
                prev = next;
            }

            if (count == 0)
            {
                Console.WriteLine("0");
                return;
            }

            var distN = a.Distinct().Count();
            var map = new int[distN];
            var dmap = new List<Tuple<int, int>>[distN];
            var ind = 0;
            var acc = new int[n + 1];
            for (int i = 0; i < m; i++)
            {
                var next = a[i];
                acc[next]++;
                if (acc[next] == 1)
                {
                    map[ind] = next;
                    dmap[ind] = g[next].Select(v => Tuple.Create(v.Key, v.Value)).OrderBy(t => t.Item1).ToList();
                    ind++;
                }
            }

            Array.Sort(map, dmap);

            var minFrom = -1;
            var minTo = -1;
            var maxVal = long.MinValue;
            for (int i = 0; i < distN; i++)
            {
                var next = map[i];
                var dic = dmap[i];

                var totalSum = dic.Sum(v => (long)v.Item2);
                var half = totalSum / 2 + totalSum % 2;

                var locSum = 0L;
                var pinTo = -1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    var nextLocSum = locSum + val.Item2;
                    if (nextLocSum == half || (nextLocSum > half && locSum < half))
                    {
                        pinTo = j;
                        break;
                    }

                    locSum = nextLocSum;
                }

                var curSum = 0L;
                var newSum = 0L;
                var newPos = dic[pinTo].Item1;
                for (int j = 0; j < dic.Count; j++)
                {
                    var val = dic[j];
                    curSum += Math.Abs(next - val.Item1) * (long)val.Item2;
                    newSum += Math.Abs(newPos - val.Item1) * (long)val.Item2;
                }

                var locMax = curSum - newSum;
                if (locMax <= 0)
                {
                    continue;
                }

                if (locMax > maxVal)
                {
                    maxVal = locMax;
                    minFrom = next;
                    minTo = newPos;
                }
            }

            var result = 0L;
            var prevM = a[0];
            if (prevM == minFrom)
            {
                prevM = minTo;
            }

            for (int i = 1; i < m; i++)
            {
                var nextM = a[i];
                if (nextM == minFrom)
                {
                    nextM = minTo;
                }

                result += Math.Abs(prevM - nextM);
                prevM = nextM;
            }

            Console.WriteLine(result);
            //var cs = new int[m];
            //for (int i = 0; i < m; i++)
            //{
            //    cs[i] = counts[a[i]];
            //}

            //Array.Sort(a, cs);

            //var total = cs.Sum();
            //var half = total / 2;
            //var seekHalf = half + total % 2;
            //var left = 0;

            //for (int i = 0; i < m; i++)
            //{
            //    var nextL = left + cs[i];
            //    if (nextL == seekHalf)
            //    {

            //    }
            //}
            //var n = readInt();
            //var m = readInt();

            //var a = readIntArray();
            //var b = readIntArray();
            #endregion
        }

        static int readInt()
        {
            return int.Parse(Console.ReadLine());
        }

        static long readLong()
        {
            return long.Parse(Console.ReadLine());
        }

        static int[] readIntArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => int.Parse(i)).ToArray();
        }

        static long[] readLongArray()
        {
            return Console.ReadLine().Split(' ').Where(i => !string.IsNullOrEmpty(i)).Select(i => long.Parse(i)).ToArray();
        }

#if DEBUG
		static StreamReader getInput()
		{
			var resName = Assembly.GetCallingAssembly().GetManifestResourceNames()[0];
			var resource = Assembly.GetCallingAssembly().GetManifestResourceStream(resName);

			return new StreamReader(resource);
		}
#endif
    }
}


from collections import defaultdict

LIM = 10 ** 5 + 123

n, m = map(int, raw_input().split())
occ = [[] for i in range(LIM)]
add = [0 for i in range(LIM)]

a = list(map(int, raw_input().split()))

base_ans = 0
for i in range(1, m):
    if a[i] != a[i - 1]:
        occ[a[i]].append(a[i - 1])
        occ[a[i - 1]].append(a[i])

    t = abs(a[i] - a[i - 1])
    base_ans += t
    add[a[i]] += t
    add[a[i - 1]] += t

ans = base_ans

for i in range(LIM):
    if len(occ[i]) == 0:
        continue

    occ[i].sort()
    k = len(occ[i])
    sum_before = 0
    sum_after = sum(occ[i])

    for idx, c in enumerate(occ[i], 1):
        sum_before += c
        sum_after -= c

        cur = idx * c - sum_before
        cur += sum_after - (k - idx) * c
        ans = min(ans, base_ans - add[i] + cur)

print(ans)


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    from builtins import str as __str__

    str = lambda x=b"": x if type(x) is bytes else __str__(x).encode()

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines += b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))

    res = 0
    neighbors = [[] for _ in range(n + 1)]
    neighbors[a[0]].append(a[1])

    for i in range(m - 2):
        res += abs(a[i + 1] - a[i])
        neighbors[a[i + 1]].extend([a[i], a[i + 2]])

    res += abs(a[-1] - a[-2])
    neighbors[a[-1]].append(a[-2])

    ans = res
    for i, x in enumerate(neighbors):
        if x:
            x = sorted(xi for xi in x if xi != i)
            median = x[len(x) // 2]
            diff = sum(abs(xi - i) for xi in x) - sum(abs(xi - median) for xi in x)
            ans = min(ans, res - diff)

    print(ans)

if __name__ == "__main__":
    main()


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    from builtins import str as __str__

    str = lambda x=b"": x if type(x) is bytes else __str__(x).encode()

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines += b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))

    res = 0
    neighbors = [[] for _ in range(n + 1)]
    neighbors[a[0]].append(a[1])

    for i in range(m - 2):
        res += abs(a[i + 1] - a[i])
        neighbors[a[i + 1]].extend([a[i], a[i + 2]])

    res += abs(a[-1] - a[-2])
    neighbors[a[-1]].append(a[-2])

    ans = res
    for i, x in enumerate(neighbors):
        x = sorted(xi for xi in x if xi != i)
        if x:
            median = x[len(x) // 2]
            diff = sum(abs(xi - i) for xi in x) - sum(abs(xi - median) for xi in x)
            ans = min(ans, res - diff)

    print(ans)

if __name__ == "__main__":
    main()


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
else:
    from builtins import str as __str__

    str = lambda x=b"": x if type(x) is bytes else __str__(x).encode()

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._buffer = BytesIO()
        self._fd = file.fileno()
        self._writable = "x" in file.mode or "r" not in file.mode
        self.write = self._buffer.write if self._writable else None

    def read(self):
        if self._buffer.tell():
            return self._buffer.read()
        return os.read(self._fd, os.fstat(self._fd).st_size)

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines += b.count(b"\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0, 2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()

    def flush(self):
        if self._writable:
            os.write(self._fd, self._buffer.getvalue())
            self._buffer.truncate(0), self._buffer.seek(0)

sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip(b"\r\n")

def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", b" "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", b"\n"))
    if kwargs.pop("flush", False):
        file.flush()

def main():
    n, m = map(int, input().split())
    a = list(map(int, input().split()))

    if m == 1:
        print(0)
        return

    res = 0
    neighbors = [[] for _ in range(n + 1)]
    neighbors[a[0]].append(a[1])

    for i in range(m - 2):
        res += abs(a[i + 1] - a[i])
        neighbors[a[i + 1]].extend([a[i], a[i + 2]])

    res += abs(a[-1] - a[-2])
    neighbors[a[-1]].append(a[-2])

    ans = res
    for i, x in enumerate(neighbors):
        x = sorted(xi for xi in x if xi != i)
        if x:
            median = x[len(x) // 2]
            diff = sum(abs(xi - i) for xi in x) - sum(abs(xi - median) for xi in x)
            ans = min(ans, res - diff)

    print(ans)

if __name__ == "__main__":
    main()


from collections import defaultdict

LIM = 10 ** 5 + 123

n, m = map(int, input().split())
occ = [[] for i in range(LIM)]
add = [0 for i in range(LIM)]

a = list(map(int, input().split()))

base_ans = 0
for i in range(1, m):
    if a[i] != a[i - 1]:
        occ[a[i]].append(a[i - 1])
        occ[a[i - 1]].append(a[i])

    t = abs(a[i] - a[i - 1])
    base_ans += t
    add[a[i]] += t
    add[a[i - 1]] += t

ans = base_ans

for i in range(LIM):
    if len(occ[i]) == 0:
        continue

    occ[i].sort()
    k = len(occ[i])
    sum_before = 0
    sum_after = sum(occ[i])

    for idx, c in enumerate(occ[i], 1):
        sum_before += c
        sum_after -= c

        cur = idx * c - sum_before
        cur += sum_after - (k - idx) * c
        ans = min(ans, base_ans - add[i] + cur)

print(ans)


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Ryouko_s_Memory_Note
{
    internal class Program
    {
        private static readonly StreamReader reader =
            new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);

        private static readonly StreamWriter writer =
            new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            string[] ss = reader.ReadLine().Split(' ');
            int n = int.Parse(ss[0]);
            int m = int.Parse(ss[1]);

            var mm = new int[m];
            var nn = new List<int>[n + 1];
            for (int i = 0; i < nn.Length; i++)
            {
                nn[i] = new List<int>();
            }
            ss = reader.ReadLine().Split(' ');
            for (int i = 0; i < m; i++)
            {
                mm[i] = int.Parse(ss[i]);
                nn[mm[i]].Add(i);
            }

            var h = new Hashtable();

            long min = 0;
            for (int i = 1; i < m; i++)
            {
                min += Math.Abs(mm[i - 1] - mm[i]);
            }

            long con = min;
            for (int i = 1; i < m; i++)
            {
                if (mm[i - 1] == mm[i])
                    continue;
                long hash = (((long) mm[i - 1]) << 32) + mm[i];
                if (h[hash] == null)
                {
                    h[hash] = 1;

                    long count = con;

                    foreach (int index in nn[mm[i - 1]])
                    {
                        if (index != 0)
                        {
                            if (mm[index - 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index - 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index - 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                        if (index != m - 1)
                        {
                            if (mm[index + 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index + 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index + 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                    }

                    if (count < min)
                        min = count;
                }
            }

            for (int i = 0; i < m - 1; i++)
            {
                if (mm[i + 1] == mm[i])
                    continue;
                long hash = (((long) mm[i + 1]) << 32) + mm[i];
                if (h[hash] == null)
                {
                    h[hash] = 1;

                    long count = con;

                    foreach (int index in nn[mm[i + 1]])
                    {
                        if (index != 0)
                        {
                            if (mm[index - 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index - 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index - 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                        if (index != m - 1)
                        {
                            if (mm[index + 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index + 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index + 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                    }

                    if (count < min)
                        min = count;
                }
            }

            writer.WriteLine(min);
            writer.Flush();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Ryouko_s_Memory_Note
{
    internal class Program
    {
        private static readonly StreamReader reader =
            new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);

        private static readonly StreamWriter writer =
            new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            string[] ss = reader.ReadLine().Split(' ');
            int n = int.Parse(ss[0]);
            int m = int.Parse(ss[1]);

            var mm = new int[m];
            var nn = new List<int>[n + 1];
            for (int i = 0; i < nn.Length; i++)
            {
                nn[i] = new List<int>();
            }
            ss = reader.ReadLine().Split(' ');
            for (int i = 0; i < m; i++)
            {
                mm[i] = int.Parse(ss[i]);
                nn[mm[i]].Add(i);
            }

            var h = new Hashtable();

            long min = 0;
            for (int i = 1; i < m; i++)
            {
                min += Math.Abs(mm[i - 1] - mm[i]);
            }

            long con = min;
            for (int i = 1; i < m; i++)
            {
                long hash = (((long) mm[i - 1]) << 32) + mm[i];
                if (h[hash] == null)
                {
                    h[hash] = 1;

                    long count = con;

                    foreach (int index in nn[mm[i - 1]])
                    {
                        if (index != 0)
                        {
                            if (mm[index - 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index - 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index - 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                        if (index != m - 1)
                        {
                            if (mm[index + 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index + 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index + 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                    }

                    if (count < min)
                        min = count;
                }
            }

            for (int i = 0; i < m - 1; i++)
            {
                long hash = (((long) mm[i + 1]) << 32) + mm[i];
                if (h[hash] == null)
                {
                    h[hash] = 1;

                    long count = con;

                    foreach (int index in nn[mm[i + 1]])
                    {
                        if (index != 0)
                        {
                            if (mm[index - 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index - 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index - 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                        if (index != m - 1)
                        {
                            if (mm[index + 1] != mm[index])
                            {
                                int deltaold = Math.Abs(mm[index + 1] - mm[index]);
                                int deltanew = Math.Abs(mm[index + 1] - mm[i]);
                                count = count - deltaold + deltanew;
                            }
                        }
                    }

                    if (count < min)
                        min = count;
                }
            }

            writer.WriteLine(min);
            writer.Flush();
        }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Ryouko_s_Memory_Note
{
    internal class Program
    {
        private static readonly StreamReader reader =
            new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);

        private static readonly StreamWriter writer =
            new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            string[] ss = reader.ReadLine().Split(' ');
            int n = int.Parse(ss[0]);
            int m = int.Parse(ss[1]);

            var mm = new int[m];
            var nn = new List<int>[n + 1];
            for (int i = 0; i < nn.Length; i++)
            {
                nn[i] = new List<int>();
            }
            ss = reader.ReadLine().Split(' ');
            for (int i = 0; i < m; i++)
            {
                mm[i] = int.Parse(ss[i]);
            }
            for (int i = 1; i < m; i++)
            {
                if (mm[i] == mm[i - 1])
                    continue;
                nn[mm[i]].Add(mm[i - 1]);
                nn[mm[i - 1]].Add(mm[i]);
            }
            for (int i = 0; i < nn.Length; i++)
            {
                nn[i].Sort();
            }

            long min = 0;
            for (int i = 1; i < m; i++)
            {
                min += Math.Abs(mm[i - 1] - mm[i]);
            }

            long con = min;
            for (int i = 0; i < nn.Length; i++)
            {
                if (nn[i].Count == 0)
                    continue;

                int next = nn[i][(nn[i].Count)/2];
                long ans = con;
                foreach (int ii in nn[i])
                {
                    ans -= Math.Abs(ii - i);
                    ans += Math.Abs(ii - next);
                }
                if (ans < min)
                    min = ans;
            }

            writer.WriteLine(min);
            writer.Flush();
        }
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Ryouko_s_Memory_Note
{
    internal class Program
    {
        private static readonly StreamReader reader =
            new StreamReader(Console.OpenStandardInput(1024*10), Encoding.ASCII, false, 1024*10);

        private static readonly StreamWriter writer =
            new StreamWriter(Console.OpenStandardOutput(1024*10), Encoding.ASCII, 1024*10);

        private static void Main(string[] args)
        {
            string[] ss = reader.ReadLine().Split(' ');
            int n = int.Parse(ss[0]);
            int m = int.Parse(ss[1]);

            var mm = new int[m];
            var nn = new List<int>[n + 1];
            for (int i = 0; i < nn.Length; i++)
            {
                nn[i] = new List<int>();
            }
            ss = reader.ReadLine().Split(' ');
            for (int i = 0; i < m; i++)
            {
                mm[i] = int.Parse(ss[i]);
                nn[mm[i]].Add(i);
            }

            var h = new Hashtable();

            long min = 0;
            for (int i = 1; i < m; i++)
            {
                min += Math.Abs(mm[i - 1] - mm[i]);
            }

            long con = min;
            for (int i = 1; i < m; i++)
            {
                long hash = (((long) mm[i - 1]) << 32) + mm[i];
                if (h[hash] == null)
                {
                    h[hash] = 1;

                    long count = con;

                    foreach (int index in nn[mm[i - 1]])
                    {
                        if (index != 0)
                        {
                            int deltaold = Math.Abs(mm[index - 1] - mm[index]);
                            int deltanew = Math.Abs(mm[index - 1] - mm[i]);
                            count = count - deltaold + deltanew;
                        }
                        if (index != m - 1)
                        {
                            int deltaold = Math.Abs(mm[index + 1] - mm[index]);
                            int deltanew = Math.Abs(mm[index + 1] - mm[i]);
                            count = count - deltaold + deltanew;
                        }
                    }

                    if (count < min)
                        min = count;
                }
            }

            for (int i = 0; i < m - 1; i++)
            {
                long hash = (((long) mm[i + 1]) << 32) + mm[i];
                if (h[hash] == null)
                {
                    h[hash] = 1;

                    long count = con;

                    foreach (int index in nn[mm[i + 1]])
                    {
                        if (index != 0)
                        {
                            int deltaold = Math.Abs(mm[index - 1] - mm[index]);
                            int deltanew = Math.Abs(mm[index - 1] - mm[i]);
                            count = count - deltaold + deltanew;
                        }
                        if (index != m - 1)
                        {
                            int deltaold = Math.Abs(mm[index + 1] - mm[index]);
                            int deltanew = Math.Abs(mm[index + 1] - mm[i]);
                            count = count - deltaold + deltanew;
                        }
                    }

                    if (count < min)
                        min = count;
                }
            }

            writer.WriteLine(min);
            writer.Flush();
        }
    }
}