Advertisement
Mehulcoder

PhonePe2019B

Oct 9th, 2020
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. /*
  2. Author: Mehul Chaturvedi
  3. */
  4.  
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7.  
  8. using ll = long long;
  9.  
  10. #define vll vector<long long>
  11. #define vset(v, n, val) v.clear(); v.resize(n, val)
  12. #define INF 4557430888798830399ll
  13. #define rep(i, n) for (int i = 0, _n = (n); i < _n; i++)
  14. #define repr(i, n) for (int i = n; i >= 0; i--)
  15.  
  16.  
  17. /*
  18. * Say we remove the num at index k.
  19. * The maximum sum, so that it lies within the current subarray
  20. * will be rMax[i] (maxPrefixSum on it's right) - lMin[j-1]
  21. * (minimum prefix sum on it's left) - a[k]
  22.  
  23. * Check the edge case when there are no negative numbers
  24. */
  25.  
  26. ll n;
  27. vll a;
  28. void solve() {
  29.     cin >> n;
  30.     vset(a, n, 0);
  31.  
  32.     rep(i, n) cin >> a[i];
  33.     vll pre(n, 0);
  34.  
  35.     rep(i, n) {
  36.         if (i != 0)
  37.             pre[i] = pre[i - 1] + a[i];
  38.         else
  39.             pre[i] = a[i];
  40.     }
  41.  
  42.     vll lMin(n, 0);
  43.     vll rMax(n, 0);
  44.  
  45.     lMin[0] = 0;
  46.     rep(i, n) {
  47.         if (i != 0) lMin[i] = min(lMin[i - 1], pre[i - 1]);
  48.     }
  49.  
  50.     ll ans = -INF;
  51.     rep(i, n) ans = max(ans, pre[i] - lMin[i]);
  52.  
  53.     rMax[n - 1] = pre[n - 1];
  54.     repr(i, n - 2) rMax[i] = max(rMax[i + 1], pre[i]);
  55.  
  56.  
  57.     rep(i, n) {
  58.         if (a[i] < 0) {
  59.             ans = max(ans, rMax[i] - lMin[i] - a[i]);
  60.         }
  61.     }
  62.  
  63.     cout << ans << '\n';
  64.     return;
  65. }
  66.  
  67. int main(int argc , char ** argv) {
  68.     ios_base::sync_with_stdio(false) ;
  69.     cin.tie(NULL) ;
  70.  
  71.     ll t = 1;
  72.     while (t--) {
  73.         solve();
  74.     }
  75.  
  76.     return 0 ;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement