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];
}
};
本文介绍了一种寻找含至少一个数的最大子数组和的方法,并给出一个O(n)复杂度的解决方案示例。针对给定数组,如[-2,1,-3,4,-1,2,1,-5,4],子数组[4,-1,2,1]具有最大和6。此外,还探讨了使用分治策略的另一种实现方式。

5565

被折叠的 条评论
为什么被折叠?



