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
#include <cstdio>

constexpr int MX = 1005;

int n, k;
int a[MX];
bool used[MX];

long long Fill(int idx, int idx_to_fill) {
  if (idx_to_fill < 0 || idx_to_fill >= n) {
    return 0;
  }
  
  long long result = 0;
  if (a[idx_to_fill] + k < a[idx]) {
    result = a[idx] - k - a[idx_to_fill];
    a[idx_to_fill] = a[idx] - k;
  }

  return result;
}

long long Round() {
  int highest_idx = -1;

  for (int i = 0; i < n; ++i) {
    if (!used[i]) {
      if (highest_idx == -1 || a[highest_idx] < a[i]) {
        highest_idx = i;
      }
    }
  }

  long long result = 0;

  used[highest_idx] = true;
  result += Fill(highest_idx, highest_idx - 1);
  result += Fill(highest_idx, highest_idx + 1);
   
  return result;
}

int main() {
  scanf("%d%d", &n, &k);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
  }

  long long result = 0;
  for (int rnd = 0; rnd < n; ++rnd) {
    result += Round();
  }
  printf("%lld\n", result);
}