其他分享
首页 > 其他分享> > leetcode53 dp and 分治

leetcode53 dp and 分治

作者:互联网

leetcode53
1.dp动态规划

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int len=nums.size();
        if(len==0) return 0;
        if(len==1) return nums[0];
        vector<int>dp(len,0);
        dp[0]=nums[0];
        int max_num=dp[0];
        int i=1;
        for(;i!=len;++i)
        {
            if(dp[i-1]>0)
                dp[i]=dp[i-1]+nums[i];
            else
                dp[i]=nums[i];
            max_num=max(dp[i],max_num);
        }
        return max_num;
    }
};

2.分治,没太懂

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
       if(!nums.size()) return 0;
       return helper(nums,0,nums.size()-1);
    }
    int helper(vector<int>&nums,int l,int r)
    {
        if(l>r) return INT_MIN;
        if(l==r) return nums[l];
        int mid=(l+r)/2;
        int left=helper(nums,l,mid-1);
        int right=helper(nums,mid+1,r);
        int t=nums[mid];
        int max_num=nums[mid];
        for(int i=mid-1;i>=0;i--)
        {
            t+=nums[i];
            max_num=max(max_num,t);
        }
        t=max_num;
        for(int i=mid+1;i<=r;i++)
        {
            t+=nums[i];
            max_num=max(max_num,t);
        }
        return max(max(left,right),max_num);
    }
};

END

标签:return,nums,int,max,分治,num,leetcode53,dp
来源: https://blog.csdn.net/kunlewang/article/details/119352905