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

int main()
{
    int n, m, k = 0, sum = 0, a[1001], b[1001];
    vector<int> v;
    
    cin >> n >> m;

    for( int i = 0; i < n; i++ )
        cin >> a[i];

    for( int i = 0; i < n; i++ )
        b[i] = 0;

    bool j = true;
    while( j )
    {
        for( int i = 0; i < m; i++ )
        {
            v.push_back(a[k]);
            b[k]++;
            k++;
            if( k == n )
                k = 0;
        }

        int min = 10000000, max = 0;
        for( int i = 0; i < v.size(); i++ )
        {
            if( min > v[i] )
                min = v[i];
            if( max < v[i] )
                max = v[i];
        }

        sum += max - min;

        j = false;
        for( int i = 0; i < n - 1; i++ )
            if( b[i] != b[i+1] )
            {
                j = true;
                break;
            }
        v.clear();
    }

    cout << sum << endl;

    return 0;
}
