动态规划---最大和的子集

1、题目:

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.

2、解答:这是选和不选的问题。若第i步的值加上num[i]小于num[i]则不选,若大于num[i],则选。


3、代码:

C++代码

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        //vector<int> f(nums.size());
        //f[0] = nums[0];
        //for(int i=1;i<nums.size();i++){
         //   f[i] = max(f[i-1]+nums[i],nums[i]);
       // }
        //return *std::max_element(f.begin(),f.end());
        int ans = nums[0];
        int sum = nums[0];
        for(int i=1;i<nums.size();i++){
            sum = max(sum + nums[i],nums[i]);
            if(sum > ans)
                ans = sum;
        }
        return ans;
    }
};

python代码

class Solution:
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sum_num = nums[0]
        ans = nums[0]
        for i in range(1,len(nums)):
            sum_num = max(sum_num+nums[i],nums[i])
            if sum_num > ans:
                ans = sum_num
        return ans

猜你喜欢

转载自blog.csdn.net/qq_31307013/article/details/80575995
今日推荐