include<stdio.h>

include

using namespace std;

const int maxn=502,maxm=102;
const int INF=0x7fffffff;

int f[maxn][maxm];
int Min[maxn];

int a[maxn];

struct Node
{
int pos,num;
}Mem[maxn];
int sz;

int col(int l,int r,int pos)
{
int res=0;

for(int i=l;i<=r;i++)
    res+=(pos-Mem[i].pos)*Mem[i].num;

return res;

}

int main(int argc, char const *argv[])
{
int n,m;
scanf("%d%d",&n,&m);

for(int i=1;i<=n;i++)
    scanf("%d",&a[i]);

sort(a+1,a+n+1);

Mem[0].pos=-m*2-2;
a[0]=-1;

for(int i=1;i<=n;i++)
{
    if( a[i]^a[i-1] )
        Mem[++sz].pos=a[i];

    Mem[sz].num++;
}

Mem[sz+1].pos=Mem[sz].pos+m+2;

for(int i=1;i<=n;i++)
{
    for(int j=1;j<=m;j++)
        f[i][j]=INF;
    Min[i]=INF;
}

Min[0]=0;

for(int i=1;i<=sz;i++)
    for(int j=0;j<min(m,Mem[i+1].pos-Mem[i].pos);j++)
    {
        int pos=Mem[i].pos+j,lpos=pos-m;

        int val=col(1,i,pos);
        f[i][j]=val;

        for(int k=0; k<i and Mem[k].pos<=lpos ;k++)
        {
            val-=(pos-Mem[k].pos)*Mem[k].num;

            //如果Mem[k+1].pos-1<=lpos,那么Min[k]照样能用(因为Mem[k+1].pos-1也是l的边界之一,只要l小于两个边界中较小的那个值,就可以直接用Min[k])
            if( min( Mem[k].pos+m-1,Mem[k+1].pos-1 )<=lpos ) f[i][j]=min( f[i][j],Min[k]+val );
            else
            {
                for(int kk=0; Mem[k].pos+kk<Mem[k+1].pos and Mem[k].pos+kk<=lpos and kk<m;kk++)
                    f[i][j]=min( f[i][j],f[k][kk]+val );
            }
        }

        Min[i]=min( Min[i],f[i][j] );
    }

printf("%d",Min[sz]);

return 0;

}