1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;

void makeFlat(vector<int> &hh, const int midIdx, const int k) {
	for (int i = midIdx - 1; i >= 0; i--) {
		if (hh[i] + k < hh[i + 1]) {
			hh[i] = hh[i + 1] - k;
		} else if (hh[i] > hh[i + 1]) {
			break;
		}
	}

	for (int i = midIdx + 1; i < (int) hh.size(); i++) {
		if (hh[i] + k < hh[i - 1]) {
			hh[i] = hh[i - 1] - k;
		} else if (hh[i] > hh[i - 1]) {
			break;
		}
	}
}

int main() {

	cin.tie(NULL);
	cout.tie(NULL);
	ios_base::sync_with_stdio(false);

	int n, k, h;

	cin >> n;
	cin >> k;

	vector<int> workingHeights(n);
	vector<int> indices(n);
	iota(indices.begin(), indices.end(), 0);

	for (int i = 0; i < n; i++) {
		cin >> h;
		workingHeights[i] = h;
	}
	const vector<int> referenceHeights(workingHeights);
	sort(indices.begin(), indices.end(), [&referenceHeights](int a, int b) {
		return referenceHeights[a] > referenceHeights[b]; // descending
	});


	for (int i = 0; i < n; i++) {
		const int midIdx = indices[i];
		makeFlat(workingHeights, midIdx, k);
	}

	int result = 0;
	for (int i = 0; i < n; i++) {
		result+=workingHeights[i] - referenceHeights[i];
	}
	cout << result << endl;
}