Leetcode 309. The best time to buy and sell stocks includes freezing period


309. The best time to buy and sell stocks includes freezing period

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


Given an array of integers, the ith element represents the stock price of the ith day. ​

Design an algorithm to calculate the maximum profit. You can do as many transactions as you can (buy and sell a stock many times) with the following constraints:

  • You can’t participate in multiple transactions at the same time (you have to sell the previous shares before you buy again).
  • You can’t buy shares the next day after you sell them.


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

Thinking of solving problems

Idea: dynamic planning

First examine the topic, the topic that can not participate in multiple transactions at the same time, before buying the need to sell the previous purchase of the stock. There will also be oneFreezing periodThe explanation given by the title is that when a stock is sold one day, it can’t be bought again the next day, that is, the day after the sell-off has a rest day.

Because there is such a freezing period in trading, we will first distinguish whether we hold stocks or not, and then add this concept to the discussion. First, two DP arrays are defined, which represent the cumulative maximum return of stocks held and stocks not held respectively.

State definition

First, the state is defined, and two arrays are definedownandnot_own。 amongown[i]Denotes the secondiThe maximum return on holding shares; andnot_own[i]Denotes the secondiDays, the maximum return on shares not held.

state transition

Let’s talk about it nowFreezing periodThis concept, the above two arrays, will have different situations during state transition, as follows:

aboutown[i]For the first timeiThe possible split of the maximum return of holding shares for three days is as follows:

  • The firsti-1Days hold, days holdiDays to continue to hold;
  • The firsti-1The first day is the freezing periodiBuy the day before yesterday (that is, sell the day before yesterday, buy the day price isprices[i]);
  • Then the state transition equation is as follows:own[i] = max(own[i-1], not_own[i-2] - prices[i])

aboutnot_own[i]It can also be divided into the following cases:

  • The firsti-1Days, daysiIt belongs to freezing period;
  • The firsti-1Day holds stock, dayiSell off the stock in three days;
  • Then the state transition equation is as follows:not_own[i] = max(not_own[i-1], own[i-1]+prices[i])

Here, a state transition occurs between two arrays. Let’s talk about it firstown[i]For the first case, it is easy to understand. For the second case, it is easy to understand, because the income of a close sale is calculated as follows: income = sell buy. Then the money needed to buy on the same day is directly deducted (that is, the purchase price is deducted first). When selling later, this part is not calculated here, and the selling price is directly added. This kind of situation is similar tonot_own[i]The second situation is consistent with the first onei-1Days of earnings plus the current stock price (as previously deducted).


own[0]: denotes the second0Days to buy, the previous analysis, here directly minus the purchase price, soown[0] = -prices[0]

own[1]: indicates that it is possible to0Days to buy, days to buy1Continue to hold; or1I bought on the same day, soown[1] = max(-prices[0], -prices[1])

not_own[0]: denotes the second0I didn’t hold any stock, so I didn’t make any profit,not_own[0] = 0

The specific code implementation is as follows.

code implementation

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

        length = len(prices)

        own = [0] * length
        not_own = [0] * length

        own[0] = -prices[0]
        own[1] = max(-prices[0], -prices[1])

        not_own[0] = 0

        for i in range(1, length):
            not_own[i] = max(not_own[i-1], own[i-1] + prices[i])
            if i == 1:
            own[i] = max(own[i-1], not_own[i-2] - prices[i])
        return max(own[-1], not_own[-1])

Implementation results

Leetcode 309. The best time to buy and sell stocks includes freezing period

Welcome to pay attention

The official account [book collection]

Recommended Today

Crawler primary operation (2)

This article is a brief introduction to the primary operation of Python web crawler, which mainly includes the following two parts: Analysis of web pages database Analysis of web pages Generally speaking, there are three ways to parse web pages: regular expression, beautiful soup and lxml. Among them, regular expression is more difficult. Beautiful soup […]