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

typedef long long ll;
const ll MOD = 1e9+7;
const ll INF = 1e18+5;
const int N = 1e5+5;
const int M = 1e4+5;

struct Block{
    int from,to;
    ll val;
    Block(int _f=0,int _t=0,ll _v=0){
        from=_f;
        to=_t;
        val=_v;
    }
};

int n,m;
ll a[N],pref[N],suf[N],b[N],t1[N],t2[N];
vector<Block>block;

void calc(ll *d){
    memset(t1,0,sizeof(t1));
    memset(t2,0,sizeof(t2));
    for(int e=1;e<(int)block.size();e++){
        t1[e]=t1[e-1]+(block[e].val-block[e-1].val)*(1LL*n+2LL*block[e-1].to);
        t2[e]=t2[e-1]+(block[e].val-block[e-1].val)*(1LL*block[e-1].to*1LL*block[e-1].to+1LL*block[e-1].to*1LL*n);
    }

    ll sum=0;
    for(int e=1;e<(int)block.size();e++){
        for(int i=block[e].from;i<=block[e].to;i++){
            int kt=i-block[e].from+1;
            ll cur=-1LL*i*1LL*i*sum+1LL*i*t1[e-1]-t2[e-1];
            cur+=(block[e].val-block[e-1].val)*1LL*kt*1LL*(1LL*n-1LL*kt);
            d[i]=cur;
        }
        sum+=block[e].val-block[e-1].val;
    }

}

int main()
{
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)cin>>a[i];
    sort(a+1,a+1+n);

    int j=1;
    block.push_back(Block(0,0,0));
    for(int i=1;i<=n;i++){
        while(j<=n&&a[i]==a[j])j++;
        block.push_back(Block(i,j-1,a[i]));
        i=j-1;
    }
    calc(pref);

    for(int i=1;i<=n;i++)b[i]=1LL*m-a[n-i+1];
    for(int i=1;i<=n;i++)a[i]=b[i];

    block.clear();
    j=1;
    block.push_back(Block(0,0,0));
    for(int i=1;i<=n;i++){
        while(j<=n&&a[i]==a[j])j++;
        block.push_back(Block(i,j-1,a[i]));
        i=j-1;
    }
    calc(suf);

    ll ans=INF;
    for(int i=0;i<=n;i++)ans=min(ans,pref[i]+suf[n-i]);

    cout<<ans;
    return 0;
}