博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Best Time to Buy and Sell Stock with Cooldown_LeetCode
阅读量:4687 次
发布时间:2019-06-09

本文共 1805 字,大约阅读时间需要 6 分钟。

#Say you have an array for which the ith element is the price of a given stock on day i.

#Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
    #You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
    #After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
#Example:
#Input: [1,2,3,0,2]
#Output: 3
#Explanation: transactions = [buy, sell, cooldown, buy, sell]
#主要思路:动态规划,从最后一步开始倒推:
#情况无非四种:
#1,Sell:持有一个股并卖出——上一步必然是2 or 3
#2,Hold:持有一个股并继续持有——上一步必然时2 or 3
#3,Buy:没有股票,买入——上一步必然是4
#4,CD:没有股票,不操作——上一步必然是1 or 4
#以i代表i时刻,Sell[i]意为"在i时刻执行Sell操作时的最大利润"
#写出四种行为的表达式:
#Sell[i] = max(Buy[i-1]+price, hold[i-1]+price)
#Hold[i] = max(Buy[i-1], hold[i-1])
#Buy[i] = CD[i-1]-price
#CD[i] = max(Sell[i-1], CD[i-1])
#“Now you want to maximize your total profit,
#but you don't know what action to take on day i such that you get the total maximum profit,
#so you try all 4 actions on every day.
#Suppose you take action 1 on day i, since there are two possible actions on day i-1, namely actions 2 and 3,
#you would definitely choose the one that makes your profit on day i more. Same thing for actions 2 and 4.
#So we now have an iterative algorithm.”——ElementNotFoundException
#另外初始的值设定很重要: At Stage 0 : sell, hold, buy, cd = 0, -prices[0], -prices[0], 0
#动态分布,从结果开始以最佳策略进行倒推论
class Solution(object):
    def maxProfit(self, prices):
        if not prices:
            return 0
        sell, hold, buy, cd = 0, -prices[0], -prices[0], 0
        for price in prices:
            sell, hold, buy ,cd = max(buy+price, hold+price), max(buy, hold), cd - price, max(sell,cd)
        return max(sell,hold,buy,cd)

转载于:https://www.cnblogs.com/phinza/p/10271275.html

你可能感兴趣的文章
谷歌浏览器,添加默认搜索引擎的搜索地址
查看>>
数据结构化与保存
查看>>
如何避免在简单业务逻辑上面的细节上面出错
查看>>
Linux shell 命令判断执行语法 ; , && , ||
查看>>
vim代码格式化插件clang-format
查看>>
RTP Payload Format for Transport of MPEG-4 Elementary Streams over http
查看>>
Java环境变量设置
查看>>
【JBPM4】判断节点decision 方法3 handler
查看>>
filter 过滤器(监听)
查看>>
node启动时, listen EADDRINUSE 报错;
查看>>
杭电3466————DP之01背包(对状态转移方程的更新理解)
查看>>
kafka中的消费组
查看>>
python--注释
查看>>
SQL case when else
查看>>
MVc Identity登陆锁定
查看>>
cdn连接失败是什么意思_关于CDN的原理、术语和应用场景那些事
查看>>
ultraedit26 运行的是试用模式_免费试用U盘数据恢复工具 – 轻松找回U盘丢失的各种数据!...
查看>>
python sum函数导入list_python sum函数iterable参数为二维list,start参数为“[]”该如何理解...
查看>>
android 练习之路 (八)
查看>>
tp5 中 model 的聚合查询
查看>>