Skip to content

Maximum subarray sum

Maximum Subarray Sum
CSES

Abridged problem statement

Given an array aa of length nn, find the maximum value of i=lra[i]\sum_{i=l}^{r} a[i] over all pairs (l,r)(l,r) with lrl\le r. In other words, find the maximum subarray sum.

Solution

Define p[i]=jia[j]p[i] = \sum_{j\le i} a[j], with p[1]=0p[-1]=0. In other words, pp is the prefix sum array of aa. Then, for a given (l,r)(l, r), the subarray sum is p[r]p[l1]p[r] - p[l-1].

Now, let us fix rr (equivalently, we could have also fixed ll, but fixing rr is more intuitive). To maximize p[r]p[l1]p[r]-p[l-1] for a fixed rr, we must minimize p[l1]p[l-1]. So we must find min1<i<lp[i]\min_{-1\lt i<l}p[i], and we can just maintain this as we iterate rr from left to right.

Code

#include <bits/stdc++.h>

using namespace std;

using int64 = long long;

int main() {
  int n;
  cin >> n;
  vector<int> a(n);
  vector<int64> p(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
    p[i] = a[i];
    if (i != 0) {
      p[i] += p[i - 1];
    }
  }

  int64 min_prefix = 0;
  int64 ans = int64(-1e15);
  for (int r = 0; r < n; ++r) {
    ans = max(ans, p[r] - min_prefix);
    min_prefix = min(min_prefix, p[r]);
  }

  cout << ans << '\n';
}