121. Best Time to Buy and Sell Stock
My accepted Python solution to LeetCode problem 121, Best Time to Buy and Sell Stock, running in 29ms.
- Difficulty: Easy
- Python
- Runtime 29ms
- Memory 26.2MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 29ms, memory 26.2MB, accepted 2026-01-02.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit