【Leetcode】【Medium】Maximum Subarray
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
.
解题思路:
题目比较简单,leetcode中有多个类似题目;
从左向右遍历,计算当前遍历到的元素之和,如果和为负,说明这些被累加的元素不会对后面序列提供“正值”的贡献,因此和值清零,继续计算;
在计算和的过程中,不断记录能取到的最大值。
注意数组中全为负数的情况。
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 int max = nums[0]; 5 int cur_sum = 0; 6 for (int i = 0; i < nums.size(); ++i) { 7 cur_sum += nums[i]; 8 if (cur_sum > max) 9 max = cur_sum; 10 if (cur_sum < 0) 11 cur_sum = 0; 12 } 13 14 return max; 15 } 16 };