栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python买卖股票的最好时机(动态规划)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python买卖股票的最好时机(动态规划)

leetcode题目:动态规划
直观做法:找极值点之差再比较

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        L = len(prices)
        if L==1:
            return 0
        min_price = prices[0]
        max_profit = 0
        i=0
        prices.append(0)
        while(iprices[i] and prices[i-1]>=prices[i]:
                min_price = min(min_price,prices[i])

        return max_profit

动态规划做法:大问题分解成小问题

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        L = len(prices)
        if L==1:
            return 0
        hold = -prices[0] #边界条件,第一天买入股票后利润
        nothold = 0 #边界条件,第一天不买入股票的利润

        for price in prices:
        	#比较当前利润高还是今天卖掉手持股票高(无论哪一天,手持股票是遇到的最低股票价格时买入)
            nothold = max(nothold, price + hold)
            #比较当前股票价格低还是今天价格低 
            hold = max(hold,-price)
        return nothold

转化成最大子列和问题

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/294484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号