卖萌的弱渣

I am stupid, I am hungry.

Best Time to Sell and Buy Stock With Cooldown

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:

1
2
3
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

Solution

  • Java
(Best-Time-to-Buy-and-Sell-Stock-with-Cooldown.java) download
1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public int maxProfit(int[] prices) {
    int sell = 0, prev_sell = 0, buy = Integer.MIN_VALUE, prev_buy;
    for (int price : prices) {
        prev_buy = buy;
        buy = Math.max(prev_sell - price, prev_buy);
        prev_sell = sell;
        sell = Math.max(prev_buy + price, prev_sell);
    }
    return sell;
}
}
  • Python
  • sell[i] 卖出操作的最大利润。它需要考虑的是,第i天是否卖出。(手上有stock在第i天所能获得的最大利润)

  • buy[i] 买进操作的最大利润。它需要考虑的是,第i天是否买进。(手上没有stock在第i天所能获得的最大利润)

若没有卖出而只买入股票,相当于-prices[i]

buy[i] = max(buy[i-1] , sell[i-2] – prices[i]) // 休息一天在买入,所以是sell[i-2]在状态转移 sell[i] = max(sell[i-1], buy[i-1] + prices[i])

(Best-Time-to-Buy-and-Sell-Stock-with-cooldown.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        #
        if len(prices) <2:
            return 0

        n = len(prices)
        buy = [0] * n
        sell = [0] * n

        # 第0天买入,第1天卖掉 或者 不卖
        sell[1] = max(0,prices[1]-prices[0])

        # 并没有卖出的时候,买入相当于-prices[i]
        buy[0] = -prices[0]
        # 要么是第一天买,要么是第二天买
        buy[1] = max(-prices[1], -prices[0])

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

        return sell[n-1]