#include <iostream>
#include <vector>

using namespace std;

vector<int> minMax(const vector<int>& v){
	vector<int> minMax;
	minMax.assign(2,v[0]);
	for(int i = 1; i < v.size();i++){
		if(minMax[0] > v[i]){
			minMax[0] = v[i];
		}
		if(minMax[1] < v[i]){
			minMax[1] = v[i];
		}
	}
	return minMax;
}


int main(){
	vector<int> v,tmp,_minMax;
	int n, m, a ,end;
	cin >> n >> m;
	for(unsigned int i = 0; i < n; i++){
		cin >> a;
		v.push_back(a);
	}
	int index = 0;
	int sum  = 0;
	do{
		end = index + m;
		if(end <= n){
			for(unsigned int i = index; i < end; i++){
				tmp.push_back(v[i]);
			}
		}else{
			end = end - n;
			for(unsigned int i = index; i < n; i++){
				tmp.push_back(v[i]);
			}
			for(unsigned int i = 0; i < end; i++){
				tmp.push_back(v[i]);
			}
		}
		_minMax = minMax(tmp);
		sum += (_minMax[1] - _minMax[0]);
		tmp.clear();
		index = end;
	}while(end != n);
	cout << sum << endl;
}