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 <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
#define vc vector
#define st first
#define nd second
#define all(a) a.begin(), a.end()
#define sz(a) (ll)a.size()
#define pub push_back
#define pob pop_back

void program() {
	ll n, k;
	cin >> n >> k;
	vc<ll> a(n);
	for (ll &ai : a)
		cin >> ai;
	
	bool s = true;
	ll ans = 0;
	while (s) {
		s = false;
		for (ll i = 1; i < n; i++)
			if (a[i] + k < a[i - 1]) {
				ans += (a[i - 1] - k - a[i]);
				a[i] = a[i - 1] - k;
				s = true;
			}
		for (ll i = n - 2; i >= 0; i--)
			if (a[i] + k < a[i + 1]) {
				ans += (a[i + 1] - k - a[i]);
				a[i] = a[i + 1] - k;
				s = true;
			}
	}
	cout << ans << "\n";
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	program();
	return 0;
}