动态规划算法

动态规划算法适用于有重叠子问题和最优子结构性质的问题。解完几道题目后,再回头读这句话会发现这总结真是精辟。
实际操作过程中,怎么拆解也非常重要。多练,出感觉。另外,此类题要敢于设置变量。比如题目一的minprice和maxprofit

以下两道题目均出自leetcode。

题目一:买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

思路:
1.前i天的最大利润 = max{前i-1天的最大利润,prices[i] - 前i-1天中最低价}
2.设定minprice 、maxprofit。则上面的公式变成循环中 新的maxprofit = max( 旧的maxprofit,prices[i]- minprice)
3. 逻辑是:遍历数组,如果当前位置的值小于最小值,则设定它为新的最小值。如果当前位置的值- 最小值 还是大于 最大值 ,则maxprofile = price[i] - minprice

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        minprice = prices[0]
        maxprofit = 0
        if n <= 1:
            return 0
        for i in range(1,n):
            if prices[i] < minprice:
                minprice = prices[i]
            elif prices[i] - minprice > maxprofit:
                maxprofit = prices[i] - minprice
        return maxprofit

题目二:最大子序和

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-subarray

思路:

res = max(res, tmp)

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        tmp = 0
        res = nums[0]
        for num in nums:
            if tmp < 0 :
                tmp = num
            else:
                tmp = tmp + num
            res = max(res, tmp)
            
        return res

以下方法更容易理解,直接得出一个新数组然后调用了系统方法,执行起来不如动态规划最优子集更快。

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        n = len(nums)
        for i in range(1,n):
            nums[i] = nums[i] + max(nums[i-1], 0)
        return max(nums)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值