fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const long long MaxN = 1e5 +5;
  4. long long n,res=0, a[MaxN];
  5. stack<long long> st;
  6. int main()
  7. {
  8. ios_base::sync_with_stdio(0);
  9. cin.tie(0);
  10. cin >> n;
  11. long long mx = LLONG_MIN;
  12. for (long long i=1; i<=n ;i++)
  13. {
  14. cin >> a[i];
  15. vector<long long> vt;
  16. while(!st.empty()&&a[i]>a[st.top()])
  17. {
  18. vt.push_back(a[st.top()]);
  19. st.pop();
  20. }
  21. vt.push_back(a[i]);
  22. st.push(i);
  23. for (long long i=0; i<vt.size()-1; i++)
  24. {
  25. res+=vt[i+1]-vt[i];
  26. }
  27. mx=max(mx,a[i]);
  28. }
  29. vector<long long> vt;
  30. while(!st.empty()&&mx>a[st.top()])
  31. {
  32. vt.push_back(a[st.top()]);
  33. st.pop();
  34. }
  35. vt.push_back(mx);
  36. for (long long i=0; i<vt.size()-1; i++)
  37. {
  38. res+=vt[i+1]-vt[i];
  39.  
  40. }
  41. cout << res;
  42.  
  43. }
  44.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Standard output is empty