LeetCode (Best Time to Buy and Sell Stock I, II, III, IV etc.)

Jing Dong
2 min readOct 29, 2020

This session includes the best time to buy and sell stock I, II, III, IV, with a cooldown, with a transaction fee.

1. Best Time to Buy and Sell Stock (Easy)

  • Code:
    # Time O(N) Space O(1), runtime = 68 ms
def maxProfit(self, prices: List[int]) -> int:

if not prices: return 0

bottom_price = float('inf')
max_profit = 0
for p in prices:
bottom_price = min(bottom_price, p)
max_profit = max(max_profit, p - bottom_price)

return max_profit

2. Best Time to Buy and Sell Stock II (Easy)

  • Code:
    # Time O(N) Space O(1)
def maxProfit(self, prices: List[int]) -> int:

if not prices: return 0

profit = 0
for i in range(1, len(prices)):
diff = prices[i] - prices[i-1]
if diff > 0:
profit += diff

return profit

3. Best Time to Buy and Sell Stock III (Hard)

  • Code:
    # Time O(N) Space O(1), runtime = 72 ms
def maxProfit(self, prices: List[int]) -> int:

if not prices: return 0

t1_price, t2_price = float('inf'), float('inf')
t1_max_profit, t2_max_profit = 0, 0
for p in prices:
t1_price = min(t1_price, p)
t1_max_profit = max(t1_max_profit, p - t1_price)

t2_price = min(t2_price, p - t1_max_profit)
t2_max_profit = max(t2_max_profit, p - t2_price)

return t2_max_profit

4. Best Time to Buy and Sell Stock IV (Hard)

  • Code:
(to be continued)

5. Best Time to Buy and Sell Stock with Cooldown (Medium):

  • Code:
    # Time O(N) Space O(1)
def maxProfit(self, prices: List[int]) -> int:

if not prices: return 0

profits = [0] * len(prices)
max_diff = -prices[0]
for i in range(1, len(prices)):

profits[i] = max(profits[i-1], prices[i] + max_diff)
cooldown = 0 if i - 2 < 0 else profits[i-2]
max_diff = max(max_diff, cooldown - prices[i])
return profits[-1]

6. Best Time to Buy and Sell Stock with Transaction Fee (Medium)

  • Code:
(to be continued)

--

--