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])
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        buy one and sell one share of the stock multiple times
        buy -> sell -> buy -> sell
        """
        profit = 0
        for i in range(1, len(prices)):
            if prices[i] > prices[i-1]:
                profit = profit + (prices[i] - prices[i-1])
        return profit
class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        """
        at most one transaction
        重點: 當價格小於當前買進最小價格時, 則最小價格就是它 然後再去算最大利潤 
        
        """
        mini = math.inf
        profit = 0
        
        for price in prices:
            mini = min(price, mini)
            profit = max(profit, price-mini)
        return profit

Last updated