Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Greedy, 每个小步骤都pick局部最优。这里的话track一个local sum,如果local sum都小于零了直接把local sum更新为0,因为扫到下一个数的时候,它本身都比它加这串小于0的数要大呀。
leetcode的OJ不需要考虑input为空的情况,实际写的时候要问清楚
实现:
class Solution { public: int maxSubArray(vector<int>& nums) { int maxSum = nums[0]; int localSum = 0; for (int num : nums){ localSum += num; maxSum = max(maxSum, localSum); localSum = max(0, localSum); } return maxSum; } };