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

#define int long long
const int MAX = 1005;
int a[MAX];
void solve() {
    int n, k;
    std::cin >> n >> k;
    for (int i = 1; i <= n; i++)
        std::cin >> a[i];
    int ans = 0;
    // int oper = 0;
    while (true) {
        // oper++;
        // if (oper > k) {
        //     break;
        // }
        bool czy = true;
        for (int i = 1; i <= n - 1; i++) {
            if (std::abs(a[i] - a[i + 1]) > k)
                czy = false;
        }
        for (int i = 1; i <= n; i++) {
            int maxi = 0;
            if (i != 1)
                maxi = std::max(maxi, a[i - 1]);
            if (i != n)
                maxi = std::max(maxi, a[i + 1]);

            if (maxi > a[i] + k) {
                ans += (maxi - k) - a[i];
                a[i] = maxi - k;
            }
        }

        if (czy)
            break;
    }

    std::cout << ans;
}

int32_t main() {
    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    std::cout.tie(0);
    int testcases = 1;
    // std::cin >> testcases;
    while (testcases--) {
        solve();
    }
    return 0;
}