309. Best Time to Buy and Sell Stock with Cooldow

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)

假设您有一个数组,其中第i个元素是第i天给定股票的价格。

设计算法以找到最大利润。 您可以通过以下限制完成任意数量的交易(即,多次买入并卖出一股股票):

  • 您不得同时进行多笔交易(即,您必须在再次购买之前卖出股票)。
  • 在您出售股票后,您无法在第二天购买股票。 (即冷却1天)

例:

Example:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

###

python 实践:

#!/usr/bin/env python
# _*_ coding:utf-8 _*_

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) < 2:
            return 0
        buy = [0] * len(prices)
        sell = [0] * len(prices)
        buy[0] = -prices[0]
        buy[1] = max(-prices[1], buy[0])
        sell[0] = 0
        sell[1] = max(prices[1] - prices[0], 0)
        for i in range(2, len(prices)):
            buy[i] = max(sell[i - 2] - prices[i], buy[i - 1])
            sell[i] = max(prices[i] + buy[i - 1], sell[i - 1])
        return max(sell)

参考网址:

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦