#include <bits/stdc++.h> using namespace std; int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int N; cin >> N; vector<pair<int, int>> st; int64_t ans = 0; for(int i = 0; i < N; i++) { int H; cin >> H; while(!st.empty() && st.back().first <= H) { auto[h, p] = st.back(); st.pop_back(); if(p & 1) ans += h; else ans -= h; } if(!st.empty() && st.back().second == i % 2); else { if(i % 2 == 0) { ans += H; st.push_back({H, i % 2}); }else { if(!st.empty()) { st.push_back({H, i % 2}); ans -= H; } } } cout << ans << '\n'; } }