LeetCode 53. Maximum Subarray

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.


题目大意:

求最大连续子序列和,贪心做法,如果当前子序列是和最大,那么第一个元素一定不是负数,那么前两个元素的和也一定不是负数,同理前三个前四个。。。,即如果当前子序列的和为负数,那么最优解一定不包含该子序列。


题目代码:

class Solution {
public:
    int maxSubArray(vector& nums) {
        int cur = 0;
        int ans = INT_MIN;
        for(int i = 0; i < nums.size(); i++){
            cur+=nums[i];
            ans = max(ans,cur);
            if(cur < 0){
                cur = 0;
            }
        }
        return ans;
    }
};




你可能感兴趣的:(LeetCode,算法设计,-,贪心法,LeetCode题解,LeetCode,Maximum,Subarray,贪心)