Maximum Subarray
题目来源:https://leetcode.com/problemset/algorithms/
-问题描述
-解题思路
-代码实现
问题描述
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.
解题思路
(1)一个子数组的和是由除了最后一项的元素的和sum和最后一个元素的值得到的。如果sum小于0,会使数组的和减小;如果sum大于0,才会使数组的和增大。则当sum小于0时,应将最后一个元素的值赋予sum.
(2)通过用数组lastsum记录每次加上一个元素之前的sum。
(3)为了确定和最大的连续子数组,应找出lastsum中最大值,并于最后的sum值比较,较大的即为连续子数组的最大和。
代码实现
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0;
vector<int> lastsum;
int i = 0;
for (vector<int>::iterator it = nums.begin(); it != nums.end(); it++, i++) {
if (it == nums.begin()) {
sum = *it;
lastsum.push_back(*it);
} else {
if (sum <= 0 ) {
sum = *it;
lastsum.push_back(*it);
} else {
lastsum.push_back(sum);
sum = sum + *it;
}
}
}
int maxlastSum = *(lastsum.begin());
for (vector<int>::iterator it = lastsum.begin(); it != lastsum.end(); it++) {
if (*it > maxlastSum) maxlastSum = *it;
}
if (maxlastSum > sum) return maxlastSum;
else return sum;
}
};