题目: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.
解析:该题目可以用动态规划方法,令 f[j] 表示以 s[j]结尾的自大连续子序列和,则
f[j]=max{f[j−1]+s[j],s[j]},其中1<=j<=n
则最大子序列和为
max{f[j]}其中1<=j<=n
代码如下:
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int max_sum = nums[0], f = nums[0];
for (int i = 1; i < nums.size(); ++i) {
f = max(f + nums[i], nums[i])
max_sum = max(max_sum, f);
}
return max_sum;
}
};
另外如果我们不仅想要求出最大连续和的子数组,还想要求出该字数组的起始位置和最终位置,则可以使用下面代码:
// 返回最大和子数组的起始位置和最终位置
class Solution {
public:
pair<int, int> maxSubArray(vector<int>& nums) {
int max_sum = nums[0], f = nums[0];
// start 和 end 表示最大连续和子数组的起始位置和最终位置
int start = 0, end = 0;
int s = 0;
for (int i = 1; i < nums.size(); ++i) {
if (f > 0)
f = f + nums[i];
else {
f = nums[i];
s = i; // 一个新的子数组序列开始位置
}
if (max_sum < f) {
max_sum = f;
end = i;
start = s;
}
}
return make_pair(start, end);
}
};