算法设计与应用基础:第十周(2)

这个帖子是针对第三周做的53题的改进,应用动态规划使得时间复杂度缩小到O(n)。


思路:搬运自leetcode:

So I change the format of the sub problem into something like: maxSubArray(int A[], int i), which means the maxSubArray for A[0:i ] which must has A[i] as the end element. Note that now the sub problem's format is less flexible and less powerful than the previous one because there's a limitation that A[i] should be contained in that sequence and we have to keep track of each solution of the sub problem to update the global optimal value. However, now the connect between the sub problem & the original one becomes clearer:

通过这一子问题的分解使得原问题的答案就变成了所有maxSubArray中的最大值,同时注意到下一个maxSubArray的计算方法是temp=temp>0?temp+nums[i]:nums[i];非常精妙的思路,主要问题简化在于maxSubArray一定包括该数组范围内最后一个。代码如下

int maxSubArray(vector<int>& nums) {
        int size=nums.size();
        int temp=nums[0];
        int Max=temp;
        for(int i=1;i<size;i++)
        {
            temp=temp>0?temp+nums[i]:nums[i];
            Max=max(Max,temp);
        }
        return Max;
    }
总结:依旧是牢牢记住动态规划的步骤:寻找子问题最优解,合理优化局部结构。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值