LeetCode solutions

123. Best Time to Buy and Sell Stock III

My accepted Python solution to LeetCode problem 123, Best Time to Buy and Sell Stock III, running in 218ms.

  • Difficulty: Hard
  • Python
  • Runtime 218ms
  • Memory 28.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 218ms, memory 28.6MB, accepted 2025-12-23.

python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy1 = buy2 = float('inf')
        profit1 = profit2 = 0
        
        for price in prices:
            buy1 = min(buy1, price)
            profit1 = max(profit1, price - buy1)
            buy2 = min(buy2, price - profit1)
            profit2 = max(profit2, price - buy2)
        
        return profit2

Source