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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define fi first
#define sn second

typedef long long ll;
typedef vector<int> VI;
typedef vector<bool> VB;
typedef vector<char> VC;
typedef pair<int, int> PI;

struct Seg {
    int x;
    int d;
};

bool operator<(Seg a, Seg b) {
    if (a.d == b.d)
        return a.x < b.x;
    return a.d > b.d;
}

int main() {
    int n, k;
    cin >> n >> k;

    VI A(n);
    vector<Seg> S(n);

    for (int i = 0; i < n; i++) {
        cin >> A[i];
        S[i].x = i;
        S[i].d = A[i];
    }

    sort(S.begin(), S.end());

    int res = 0;

    for (int i = 0; i < n; i++) {
        int x = S[i].x;
        if (S[i].d != A[x])
            continue;

        for (int j = x - 1; j >= 0; j--) {
            if (A[j + 1] - A[j] > k) {
                int d = A[j + 1] - A[j] - k;
                res += d;
                A[j] += d;
            }
            else {
                break;
            }
        }
        for (int j = x + 1; j < n; j++) {
            if (A[j - 1] - A[j] > k) {
                int d = A[j - 1] - A[j] - k;
                res += d;
                A[j] += d;
            }
            else {
                break;
            }

        }
        // cout << S[i].x << " " << S[i].d << " " << res << endl;
    }

    cout << res << endl;

    return 0;
}