#include #include using namespace std; // Try to start in each local minimum. // For each of them, repeatedly expand the range to the side with the lower new value. // Do not break when the answer gets too large. int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector v(n); for(auto& x : v) cin >> x; v.reserve(4 * n); for(auto x : v) v.push_back(x); for(auto x : v) v.push_back(x); long long ans = 1e18; for(int i = n; i < 2 * n; ++i) { if(v[i - 1] < v[i] or v[i] > v[i + 1]) continue; int l = i, r = i; long long s = 0, t = 0; while(r - l < n) { auto e = v[l - 1] < v[r] ? --l : r++; if(v[e] > t) s += v[e] - t, t = v[e]; t += v[e]; } ans = min(ans, s); } cout << ans << endl; }