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.
class Solution {
public:
int maxSubArray(int A[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int* f = new int[n+1];
int* g = new int[n+1];
f[0] = 0;
g[0] = INT_MIN;
for(int i = 1; i < n+1; i++)
{
f[i] = max(A[i-1], A[i-1]+f[i-1]);
g[i] = max(f[i],g[i-1]);
}
return g[n];
}
};