[LeetCode in Python] 309 (M) best time to buy and sell stock with cooldown best time to buy and sell shares with the freezing of

topic:

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

Given an array of integers, which represents the i-th element of the i-day stock price.

Design an algorithm to calculate the maximum profit. In the following constraints, you can close more deals as possible (buy and sell a stock):

You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).
After selling the stock, you can not buy the stock the next day (ie freeze to one day).

Example:

Input: [1,2,3,0,2]
Output: 3
Explanation: corresponding transaction status is: [buy, sell, freezing period, buy, sell]

Problem-solving ideas

  • DP
  • Set two states, hold [i] and unhold [i], respectively, represents the i-day hold and does not hold shares of the largest profit
  • Computing base state, the results are written i = 0 and i = 1
  • Write recursion formulas, because of freezing, so the value used to push the i-2 and i-1 before the

Code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # - sanity check
        if (not prices) or (len(prices)==1):
            return 0

        n = len(prices)

        # - dp state
        # - hold[i] means max profit if hold stock at day i
        # - unhold[i] means max profit if not hold stock at day i
        hold = [0] * n
        unhold = [0] * n

        # - base state

        # - hold at day 0 means buy at day 0
        hold[0] = -prices[0]

        # - hold at day 1 means:
        # -   buy at day 0, do nothing at day 1
        # -   or do nothing at day 0, and buy at day 1
        hold[1] = max(-prices[0], -prices[1])

        # - unhold at day 0
        unhold[0] = 0

        # - unhold at day 1 means:
        # -     do nothing at day 0 and day 1
        # -     buy at day 0 and sell at day 1
        unhold[1] = max(0, hold[0]+prices[1])

        # - dp formula

        # - hold[i] = max of
        # -     hold at day i-1, do nothing at day i
        # -     unhold at day i-2, do nothing at day i-1, buy at day i
        # - hold[i] = max(hold[i-1], (unhold[i-2] - prices[i]))

        # - unhold[i] = max of
        # -     unhold at day i-1, do nothing at day i
        # -     hold at day i-1, sell at day i
        # - unhold[i] = max(unhold[i-1], (hold[i-1] + prices[i]))

        for i in range(2, n):
            hold[i] = max(hold[i-1], (unhold[i-2] - prices[i]))
            unhold[i] = max(unhold[i-1], (hold[i-1] + prices[i]))

        return max(hold[n-1], unhold[n-1])

Guess you like

Origin www.cnblogs.com/journeyonmyway/p/12549797.html
Recommended