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
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
#include <time.h>
#include <queue>

using namespace std;

int main () {
	int n, k;
	scanf ("%d %d", &n, &k);
	vector<int> heights(n, 0);
	vector<bool> done(n, false);
	for (int i = 0; i < n; ++i) {
		scanf("%d", &heights[i]);
	}
	int res = 0;
	for (int i = 0; i < n; ++i) {
		int max_idx = -1;
		int max_height = -1;
		for (int j = 0; j < n; ++j) {
			if (done[j]) {
				continue;
			}
			if (heights[j] > max_height) {
				max_height = heights[j];
				max_idx = j;
			}
		}
		if (max_idx > 0 && heights[max_idx - 1] < max_height - k) {
			res += max_height - k - heights[max_idx - 1];
			heights[max_idx - 1] = max_height - k;
		}
		if (max_idx < n - 1 && heights[max_idx + 1] < max_height - k) {
			res += max_height - k - heights[max_idx + 1];
			heights[max_idx + 1] = max_height - k;
		}
		done[max_idx] = true;
	}
	printf("%d\n", res);
	return 0;
}