leetcode 53. Maximum Subarray DP

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.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 题目链接:https://leetcode.com/problems/maximum-subarray/

思路:首先用sum对数列求和,如果求和sum<0,小于0,肯定不可能是最大子序列的组成部分,所以重置为0。对于res,用sum+nums[i],来更新res

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

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/86506033