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

#define ll long long
#define pi std::pair<int, int>
#define pll std::pair<ll, ll>
#define vi std::vector<int>
#define vll std::vector<ll>
#define vpi std::vector<pi>
#define vpll std::vector<pll>
#define si std::set<int>

void solve() {
    ll n, k, sum = 0;
    std::cin >> n >> k;

    vll tab(n);
    std::set<pi> v;
    for(int i = 0; i < n; i++) {
        std::cin >> tab[i];
        v.insert({tab[i], i});
    }
    
    while(!v.empty()) {
        pi x = *v.begin();
        v.erase(v.begin());

        if(x.second != 0 && tab[x.second] - tab[x.second - 1] > k) {
            ll add = tab[x.second] - tab[x.second - 1] - k;
            sum += add;
            v.erase({tab[x.second - 1], x.second - 1});
            tab[x.second - 1] += add;
            v.insert({tab[x.second - 1], x.second - 1});
        }

        if(x.second != n-1 && tab[x.second] - tab[x.second + 1] > k) {
            ll add = tab[x.second] - tab[x.second + 1] - k;
            sum += add;
            v.erase({tab[x.second + 1], x.second + 1});
            tab[x.second + 1] += add;
            v.insert({tab[x.second + 1], x.second + 1});
        }
    }

    std::cout << sum << '\n';

}

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

    int t = 1;
    //std::cin >> t;
    while(t--) {
        solve();
    }
}