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

int main(){
        ios_base::sync_with_stdio(false);
    cin.tie(0);
    int n, k;
    cin >> n >> k;
    vector<int> arr(n);
    priority_queue<pair<int, int>> kol;
    for(int i = 0; i < n; i++){
        cin >> arr[i];
        kol.push({arr[i], i});
    }
    ll ans = 0;
    while(!kol.empty()){
        auto [val, x] = kol.top();
        kol.pop();
        if(val != arr[x]){
            continue;
        }
        if(x != 0){
            if(arr[x-1] + k < arr[x]){
                ans -= arr[x-1];
                arr[x-1] = arr[x] - k;
                ans += arr[x-1];
                kol.push({arr[x-1], x-1});
            }
        }
        if(x != n - 1){
            if(arr[x+1] + k < arr[x]){
                ans -= arr[x+1];
                arr[x+1] = arr[x] - k;
                ans += arr[x+1];
                kol.push({arr[x+1], x+1});
            }
        }
    }

    cout << ans << '\n';

    

}