Maximum subarray sum
Maximum Subarray Sum
CSES
Abridged problem statement
Given an array of length , find the maximum value of over all pairs with . In other words, find the maximum subarray sum.
Solution
Define , with . In other words, is the prefix sum array of . Then, for a given , the subarray sum is .
Now, let us fix (equivalently, we could have also fixed , but fixing is more intuitive). To maximize for a fixed , we must minimize . So we must find , and we can just maintain this as we iterate 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';
}