[Problem]
[Solution]
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
.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
[Solution]
class Solution {说明:版权所有,转载请注明出处。 Coder007的博客
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 0)return 0;
int sum[n], res = A[0];
for(int i = 0; i < n; ++i){
if(i == 0){
sum[i] = A[i];
}
else{
sum[i] = max(sum[i-1] + A[i], A[i]);
}
res = max(res, sum[i]);
}
return res;
}
};