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
#include <bits/stdc++.h>
using namespace std;

#define loop(i, a, b) for(int i = a; i <= b; i++)
#define loop_rev(i, a, b) for(int i = a; i >= b; i--)
#define all(x) x.begin(), x.end()
#define sz(x) int(x.size())
#define eb emplace_back
#define pb push_back

using ui = uint32_t;
using ll = int64_t;

int main() {
  cin.tie(0)->sync_with_stdio(0);
  int n, k; cin >> n >> k;

  vector<int> a(n + 1), t(n + 1);

  priority_queue<pair<int, int>> pq;

  for(int i = 1; i <= n; i++) {
    cin >> a[i];
    pq.push({ a[i], i });
  }

  ll res = 0;

  while(!pq.empty()) {
    auto [ val, i ] = pq.top(); pq.pop();
    if(a[i] != val) continue;
    for(int ind : { i - 1, i + 1 }) {
      if(ind < 1 || ind > n) continue;
      if(a[ind] < a[i] - k) {
        res += (a[i] - k) - a[ind];
        a[ind] = (a[i] - k);
        pq.push({ a[ind], ind });
      }
    }
  }

  cout << res << '\n';

}