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
.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
分析:考虑下标为i的元素,如果前面的元素之和小于0,那么对于增大在该元素的和是没有作用的。所以,将前面的和置为0. 运行时间14ms。
1 class Solution { 2 public: 3 int maxSubArray(vector<int>& nums) { 4 int sum = nums[0]; 5 int maxSum = nums[0]; 6 for(int i = 1; i < nums.size(); i++){ 7 if(sum < 0) sum = 0; 8 sum += nums[i]; 9 maxSum = maxSum > sum ? maxSum : sum; 10 } 11 return maxSum; 12 } 13 };