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
.
class Solution {
public:
int maxSubArray(int A[], int n) {
if(n == 0) return 0;
if(n == 1) return A[0];
int max = A[0];
int currentsum = A[0];
for(int ii = 1; ii < n; ii ++) {
if(currentsum + A[ii] > 0) {
if(currentsum < 0)
currentsum = 0;
currentsum += A[ii];
if(currentsum > max) {
max = currentsum;
}
}
else
{
if(currentsum > A[ii]) {
if(currentsum > max) {
max = currentsum;
}
}
else {
if(A[ii] > max) {
max = A[ii];
}
}
currentsum = A[ii];
}
}
return max;
}
};