#include "bits/stdc++.h" using namespace std; #define DEBUG(x) cout<<#x<<": "< #define vl vector #define vii vector< vector > #define vll vector< vector > #define vs vector #define pii pair #define pis pair #define psi pair #define pll pair const int inf = 1000000001; const ll INF = 1e18 * 4; #define MOD 1000000007 #define mod 1000000009 #define pi 3.14159265358979323846 #define Sp(p) cout<> n >> p; vl h(n + 1); for (i = 1; i <= n; i++) { cin >> h[i]; } vector vm; int left = 0, right = 1; int now = 1; while (right < n) { mountain tmp; tmp.left = left; while (h[left] <= h[now] && h[now] <= h[now + 1]) { now++; if (now == n) { tmp.top = now - 1; tmp.right = now; break; } } tmp.top = now; now++; if (now == n) { tmp.right = now - 1; break; } while (h[left] >= h[now] && h[now] >= h[now + 1]) { now++; if (now == n) { tmp.right = now; break; } } tmp.right = now; vm.push_back(tmp); left = right; } int m = vm.size(); vll cost(m, vl(3)); for (i = 0; i < m; i++) { ll up = 0; for (j = vm[i].left; j < vm[i].top; j++) { up += min(p, h[j + 1] - h[j]); } cost[i][0] = up; up = 0; for (j = vm[i].right; j > vm[i].top; j--) { up += min(p, h[j - 1] - h[j]); } cost[i][1] = up; cost[i][2] = p * 2; } vll dp(m + 1,vl(2, INF)); dp[0][0] = 0; for (i = 0; i < m; i++) { dp[i + 1][0] = min(dp[i + 1][0], dp[i][0] + min(cost[i][0], cost[i][2])); dp[i + 1][0] = min(dp[i + 1][0], dp[i + 1][1] + min(cost[i][2], p + cost[i][0])); dp[i + 1][1] = min(dp[i + 1][1], dp[i][1] + cost[i][1]); dp[i + 1][1] = min(dp[i + 1][1], dp[i][0] + p + min(p, cost[i][1])); } cout << dp[m][0] + dp[m][1] << endl; }