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
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];

    long long trucks = 0;

    // left to right: handles drops (a[i-1] much higher than a[i])
    for (int i = 1; i < n; i++) {
        int needed = max(a[i], a[i-1] - k);
        trucks += needed - a[i];
        a[i] = needed;
    }

    // right to left: handles rises (a[i+1] much higher than a[i])
    for (int i = n-2; i >= 0; i--) {
        int needed = max(a[i], a[i+1] - k);
        trucks += needed - a[i];
        a[i] = needed;
    }

    cout << trucks << endl;
}