Skip to main content

#121. Best Time to Buy and Sell Stock | LeetCode Python Solution

Problem

LeetCode Problem

  1. Best Time to Buy and Sell Stock

Python Solution

We use sliding window technique to detect best day to buy and keep track of maximum profit.

class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
Drawing to walk through the algorithm in different tests
https://excalidraw.com/#json=RdBdGSRzQzSvdtAkNf4f-,hDL4m4lrm6Hzi73m_XCoxQ
"""

# Initialize to buy at day 1 and sell at day 2
buy, sell = 0, 1

# Keep tracking of maximum profit so far
maxProfitSoFar = 0

while sell < len(prices):
profit = prices[sell] - prices[buy]

if profit < 0:
# No profit, but we found a lower price point to buy
buy = sell
else:
# Update maximum profit
maxProfitSoFar = max(maxProfitSoFar, profit)

# Increment sell day by 1
sell += 1

return maxProfitSoFar