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

int gcd(int a, int b) {return b?gcd(b, a%b):a;}
int lcm(int a, int b) {return a/gcd(a, b)*b;}

int main() {
    int n, m; cin >> n >> m;
    vector<int> a(n);
    for(int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int max_loop = lcm(n, m);
    int ans = 0;
    for (int i = 0; i < max_loop;) {
        int mx = -1e9, mn = 1e9;
        for (int j = 0; j < m; i++, j++) {
            mx = max(mx, a[i%n]);
            mn = min(mn, a[i%n]);
        }
        ans += mx - mn;
    }
    cout << ans << endl;
}
