pydata

Keep Looking, Don't Settle

leetcode 309. Best Time to Buy and Sell Stock with Cooldown

309. Best Time to Buy and Sell Stock with Cooldown

题目大意:给定一个数组,第i个元素表示第i天的股票价格。每天只能最多一次买或者卖(必须有股票才能卖)。卖了以后第二天不能买(cooldown)。求最大的利润。

解题思路:

动态规划

class Solution(object):
    def maxProfit(self, prices):
        sold = 0
        rest = 0
        hold = -float('inf')
        for price in prices:
            prev_sold = sold
            sold = hold + price
            hold = max(hold, rest - price)
            rest = max(rest, prev_sold)
        return max(rest, sold)