zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock with Cooldown_LeetCode

    #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)

  • 相关阅读:
    luogu 2627 修剪草坪
    luogu2746 [USACO5.3]校园网Network of Schools
    luogu 1558 色板游戏
    luogu 2827 蚯蚓
    POJ 2559 Largest Rectangle in a Histogram
    luogu 1886 滑动窗口
    luogu 1090 合并果子
    uva 11572
    uva 12626
    uva 10222
  • 原文地址:https://www.cnblogs.com/phinza/p/10271275.html
Copyright © 2011-2022 走看看