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 <iterator>
using namespace std;

int main() {
    cin.tie(0)->sync_with_stdio(0);
    unsigned n,k;cin>>n>>k;
    long res=0;
    unsigned tab[n];
    for (auto&& t : tab)cin>>t;
    for (unsigned i=0;i<n;++i) {
        unsigned maxv=k,id=-1;
        for (unsigned i=0;i<n;++i)
            if (tab[i]!=-1u&&tab[i]>maxv)
                maxv=tab[i],id=i;
        if (id==-1u) break;
        if (id&&maxv-k>tab[id-1]) {
            res+=maxv-k-tab[id-1];
            tab[id-1]=maxv-k;
        }
        if (id+1<n&&maxv-k>tab[id+1]) {
            res+=maxv-k-tab[id+1];
            tab[id+1]=maxv-k;
        }
        tab[id]=-1;
    }
    cout << res;
}