#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
	int n, m;	cin >> n >> m;
	vector<int> a(n);
	for (int i = 0; i < n; i++)	cin >> a[i];
	int cur = 0, ret = 0;
	do{
		int sml = 100, big = 0;
		for (int i = 0; i < m; i++) {
			sml = min(sml, a[cur]);
			big = max(big, a[cur]);
			cur = (cur + 1) % n;
		}
		ret += big - sml;
	} while (cur != 0);
	cout << ret << endl;
}