题目:
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
.
大意:给定一个序列找到当中连续子序列和的最大值
解题思路:这道题目如果直接使用暴力算法是log(n^2)的复杂度,这里利用一个事实即如果当前节点与其之前的和小于当前节点则重置runningsum的值为当前节点的值,数学表达 runningsum = max(runningsum+A[i], A[i]),这样可以动态的改变子序列的起点,使得在O(n)的复杂度下就可以解决。代码如下:
class Solution {
public:
int max(const int &a, const int &b){
return a > b ? a : b;
}
// Basic idea is that runningsum = max(A[i]+runningsum, runningsum)
int maxSubArray(int A[], int n) {
if(n == 1)
return A[0];
int sum_max = A[0];
int runningsum = A[0];
for(int i = 1; i < n; ++i){
runningsum = max(A[i] + runningsum, A[i]);
sum_max = max(runningsum, sum_max);
}
return sum_max;
}
};