Best Time to Buy and Sell Stock

LeetCode 121, 122, extra, 309, 714

class Solution:
    def maxProfit(self, prices):
        """
        [2, 1, 4, 3, 1, 2]
        buy many shares of the stock multiple times
        """
        profit = 0
        maxi = prices[-1]
        for i in range(len(prices)-2, -1, -1):
            if prices[i] < maxi:
                profit = profit + (maxi-prices[i])
            else:
                maxi = prices[i]
        return profit

Best Time to Buy and Sell Stock with Cooldown

import math
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        s0 = [0]*len(prices)
        s1 = [0]*len(prices)
        s2 = [0]*len(prices)
        s0[0] = 0
        s1[0] = -prices[0]
        s2[0] = -math.inf
        
        for i in range(1, len(prices)):
            s0[i] = max(s0[i-1], s2[i-1])
            s1[i] = max(s0[i-1] - prices[i], s1[i-1])
            s2[i] = s1[i-1] + prices[i]
        
        return max(s2[len(prices)-1], s0[len(prices)-1])

Last updated