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
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <set>


using namespace std;


using vi = vector<int>;
using pii = pair<int, int>;


#define ff first 
#define ss second


int main() {    
    ios_base::sync_with_stdio(0);
    cin.tie(0);

    int n, k;
    cin >> n >> k;

    vi tab(n);
    set<pii> secik;
    for (int i = 0; i < n; i++) {
        cin >> tab[i];
        secik.insert({-tab[i], i});
    }

    long long ans = 0;

    while (!secik.empty()) {
        int val = -(*secik.begin()).ff;
        int idx = (*secik.begin()).ss;
        secik.erase(secik.begin());

        if (idx > 0) {
            if (tab[idx] - k > tab[idx - 1]) {
                secik.erase({-tab[idx - 1], idx - 1});
                ans += tab[idx] - k - tab[idx - 1];
                tab[idx - 1] = tab[idx] - k;
                secik.insert({-tab[idx - 1], idx - 1});
            }
        }
        if (idx < n - 1) {
            if (tab[idx] - k > tab[idx + 1]) {
                secik.erase({-tab[idx + 1], idx + 1});
                ans += tab[idx] - k - tab[idx + 1];
                tab[idx + 1] = tab[idx] - k;
                secik.insert({-tab[idx + 1], idx +1});
            }
        }

    }

    cout << ans << '\n';



    return 0;
}