Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [−2,1,−3,4,−1,2,1,−5,4]
,
the contiguous subarray [4,−1,2,1]
has the largest sum = 6
.
最经典的DP问题,有空间复杂度O(1)的做法,不过我觉得这样更好理解
class Solution {
public:
int maxSubArray(int A[], int n) {
vector<int> sums(A,A+n);
for(int i = 1;i<sums.size();++i){
if(sums[i-1]>0){
sums[i] +=sums[i-1];
}
}
return *max_element(sums.begin(),sums.end());
}
};