#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
// Nhập độ cao
for (int i = 0; i < n; i++) {
cin >> a[i];
}
// Tạo mảng pref_max và suff_max
vector<int> pref_max(n), suff_max(n);
// Tính pref_max
pref_max[0] = a[0];
for (int i = 1; i < n; i++) {
pref_max[i] = max(pref_max[i - 1], a[i]);
}
// Tính suff_max
suff_max[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0; i--) {
suff_max[i] = max(suff_max[i + 1], a[i]);
}
// Tính tổng lượng nước đọng
long long ans = 0;
for (int i = 0; i < n; i++) {
ans += max(0, min(pref_max[i], suff_max[i]) - a[i]);
}
cout << ans << '\n';
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8YWxnb3JpdGhtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBtYWluKCkgewogICAgaW9zX2Jhc2U6OnN5bmNfd2l0aF9zdGRpbyhmYWxzZSk7CiAgICBjaW4udGllKG51bGxwdHIpOwoKICAgIGludCBuOwogICAgY2luID4+IG47CiAgICB2ZWN0b3I8aW50PiBhKG4pOwoKICAgIC8vIE5o4bqtcCDEkeG7mSBjYW8KICAgIGZvciAoaW50IGkgPSAwOyBpIDwgbjsgaSsrKSB7CiAgICAgICAgY2luID4+IGFbaV07CiAgICB9CgogICAgLy8gVOG6oW8gbeG6o25nIHByZWZfbWF4IHbDoCBzdWZmX21heAogICAgdmVjdG9yPGludD4gcHJlZl9tYXgobiksIHN1ZmZfbWF4KG4pOwoKICAgIC8vIFTDrW5oIHByZWZfbWF4CiAgICBwcmVmX21heFswXSA9IGFbMF07CiAgICBmb3IgKGludCBpID0gMTsgaSA8IG47IGkrKykgewogICAgICAgIHByZWZfbWF4W2ldID0gbWF4KHByZWZfbWF4W2kgLSAxXSwgYVtpXSk7CiAgICB9CgogICAgLy8gVMOtbmggc3VmZl9tYXgKICAgIHN1ZmZfbWF4W24gLSAxXSA9IGFbbiAtIDFdOwogICAgZm9yIChpbnQgaSA9IG4gLSAyOyBpID49IDA7IGktLSkgewogICAgICAgIHN1ZmZfbWF4W2ldID0gbWF4KHN1ZmZfbWF4W2kgKyAxXSwgYVtpXSk7CiAgICB9CgogICAgLy8gVMOtbmggdOG7lW5nIGzGsOG7o25nIG7GsOG7m2MgxJHhu41uZwogICAgbG9uZyBsb25nIGFucyA9IDA7CiAgICBmb3IgKGludCBpID0gMDsgaSA8IG47IGkrKykgewogICAgICAgIGFucyArPSBtYXgoMCwgbWluKHByZWZfbWF4W2ldLCBzdWZmX21heFtpXSkgLSBhW2ldKTsKICAgIH0KCiAgICBjb3V0IDw8IGFucyA8PCAnXG4nOwogICAgcmV0dXJuIDA7Cn0=