
一、核心思路
利用前缀和进行预处理,再遍历前缀和数组,计算每个位置的最大子段和并动态更新。
二、代码实现
cpp
typedef long long LL;
const int N = 2e5 + 10;
LL st[N], n;
int main()
{
cin >> n;
LL premin = 0;
LL ret = -1e10;
for (int i = 1; i <= n; i++)
{
int x; cin >> x;
st[i] = st[i-1] + x;
}
for (int i = 1; i <= n; i++)
{
ret = max(ret, st[i] - premin);
premin = min(premin, st[i]);
}
cout << ret << endl;
return 0;
}