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
#include <bits/stdc++.h>
using namespace std;
#define TF(i, p, q) for(int i = (p); i <= (q); ++i)
#define TR(i, q, p) for(int i = (q); i >= (p); --i)
#define V vector
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define th third
#define rz resize
#define all(V) V.begin(), V.end()
#define rall(V) V.rbegin(), V.rend()
#define sz(V) (int)(V.size())
#define cmin(a, b) a = min(a, b)
#define cmax(a, b) a = max(a, b);
typedef pair<int,int> ii;
typedef queue<int> qi;
typedef queue<ii> qii;
typedef long long ll; 
typedef vector<int> vi;
typedef vector<vector<int>>vvi;
typedef vector<vector<bool>>vvb;
typedef vector<bool> vb;
typedef vector<ii> vii;
constexpr int inf = 1e9 + 9;
void solve(){
    int n, k; cin >> n >> k;
    vi tab(n+1); int midx = 0;
    TF(i, 1, n){
        cin >> tab[i];
        if(tab[i] > tab[midx]) midx = i;
    }
    int score = 0;
    TF(i, midx+1, n){
        if(tab[i]-tab[i-1] <= k){
            if(tab[i-1]-tab[i] > k){
                score += tab[i-1]-k-tab[i];
                tab[i] = tab[i-1]-k;
            }
            continue;
        }
        TR(j, i-1, midx+1){
            if(abs(tab[j]-tab[j+1]) <= k) break;
            score += tab[j+1]-k-tab[j];
            tab[j] = tab[j+1]-k;
        }
    }
    TR(i, midx-1, 1){
        if(tab[i]-tab[i+1] <= k){
            if(tab[i+1]-tab[i] > k){
                score += tab[i+1]-k-tab[i];
                tab[i] = tab[i+1]-k;
            }
            continue;
        }
        TF(j, i+1, midx-1){
            if(abs(tab[j]-tab[j-1]) <= k) break;
            score += tab[j-1]-k-tab[j];
            tab[j] = tab[j-1]-k;
        }
    }
    cout << score;
}
int32_t main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0); solve();
}