Maximum Subarray Sum
题目描述
Given an array of n integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray.
输入
The first input line has an integer n(): the size of the array.
The second line has n integers x1,x2,...,xn(): the array values.
输出
Print one integer: the maximum subarray sum.
样例输入
8
-1 3 -2 5 3 -5 2 2
样例输出
9
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>n;vector<ll>x(n+1);vector<ll>current_sum(n+1);vector<ll>max_sum(n+1);ll l=0;for(ll i=1;i<=n;i++){cin>>x[i];if(i==1){current_sum[i]=x[i];max_sum[i]=x[i];}else{current_sum[i]=l+x[i];max_sum[i]=max(current_sum[i],max_sum[i-1]);}l=max(current_sum[i],(ll)0);}cout<<max_sum[n];return 0;
}