1. 程式人生 > >動態規劃---最大和的子集

動態規劃---最大和的子集

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