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

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

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.051e.com
本文地址:http://www.051e.com/it/294484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号