LeetCode - 53. Maximum Subarray - C++
2018-03-15 17:15
597 查看
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.For example, given the array
the contiguous subarray
解题思路:如果用蛮力法这道题的代码就很好写,但是时间复杂度是O(n^2),通过分析后采用以下算法可以使时间复杂度降为O(n)。首先我们可以肯定的有:
1. 如果这个数组全部都是小于等于0的数,那么返回最大值就可以了。
2. 其他情况这个数组至少有1个正数,subarray的开头一个数字一定是大于0的,如果subarray的开头数字是小于0的,那么把这个数字去掉剩下的部分的加和一定大于subarray。
3. 数组至少有1个正数,那么subarray的结尾一个数字也一定是大于0的,原理同上。
我们可以从index=0开始,得到1个、2个、3个......连续数字的和sum,并且保留最大和;一旦加了m个数后sum<0了,那么可以把前面m个数字看成是1个负数,那么根据我们第2点,这个负数就可以不被考虑进后续的加和之中,index就可以从m+1开始,并且将sum清零,重新开始之前所述的步骤。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int length = nums.size();
int pos = 0;
int sum = 0;
int maxSum = INT_MIN;
int bestPos = 0;
int count = 0;
int bestCount = 0;
while (pos < length) {
count++;
sum += nums[pos];
if (sum > maxSum) {
maxSum = sum;
bestPos = pos;
bestCount = count;
}
if (sum > 0) {
pos++;
}
else {
sum = 0;
pos++;
count = 0;
}
}
return maxSum;
}
};
[-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray
[4,-1,2,1]has the largest sum =
6.
解题思路:如果用蛮力法这道题的代码就很好写,但是时间复杂度是O(n^2),通过分析后采用以下算法可以使时间复杂度降为O(n)。首先我们可以肯定的有:
1. 如果这个数组全部都是小于等于0的数,那么返回最大值就可以了。
2. 其他情况这个数组至少有1个正数,subarray的开头一个数字一定是大于0的,如果subarray的开头数字是小于0的,那么把这个数字去掉剩下的部分的加和一定大于subarray。
3. 数组至少有1个正数,那么subarray的结尾一个数字也一定是大于0的,原理同上。
我们可以从index=0开始,得到1个、2个、3个......连续数字的和sum,并且保留最大和;一旦加了m个数后sum<0了,那么可以把前面m个数字看成是1个负数,那么根据我们第2点,这个负数就可以不被考虑进后续的加和之中,index就可以从m+1开始,并且将sum清零,重新开始之前所述的步骤。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
int length = nums.size();
int pos = 0;
int sum = 0;
int maxSum = INT_MIN;
int bestPos = 0;
int count = 0;
int bestCount = 0;
while (pos < length) {
count++;
sum += nums[pos];
if (sum > maxSum) {
maxSum = sum;
bestPos = pos;
bestCount = count;
}
if (sum > 0) {
pos++;
}
else {
sum = 0;
pos++;
count = 0;
}
}
return maxSum;
}
};
相关文章推荐
- 【C++】【LeetCode】53. Maximum Subarray
- Leetcode解题笔记 53. Maximum Subarray [Easy] 动态规划
- Leetcode 53. Maximum Subarray
- 【leetcode】53. Maximum Subarray 连续子序列的最大和
- Leetcode——53. Maximum Subarray
- leetcode 53. Maximum Subarray
- leetcode 53. Maximum Subarray
- Leetcode 53. Maximum Subarray
- leetcode 53. Maximum Subarray
- leetcode:53. Maximum Subarray
- [leetcode] 53. Maximum Subarray
- leetcode_c++:Minimum Size Subarray Sum (209)
- Leetcode题解 - 53. Maximum Subarray
- leetcode 53. Maximum Subarray
- 【leetcode】53. Maximum Subarray
- leetcode -- 53. Maximum Subarray
- [LeetCode]53. Maximum Subarray
- leetcode 53. Maximum Subarray
- [勇者闯LeetCode] 53. Maximum Subarray
- LeetCode 53. Maximum Subarray