- Leetcode Learning System
- Posts
- Day 4 - Best Time to Buy and Sell a Stock
Day 4 - Best Time to Buy and Sell a Stock
🔍 Examples:
Example 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1), sell on day 5 (price = 6). Profit = 6 - 1 = 5.
Example 2
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: No opportunity to make a profit.
📏 Constraints:
1 <= prices.length <= 10⁵
0 <= prices[i] <= 10⁴
🧠 How to Approach It
This one’s a classic example of a one-pass greedy solution.
You’re tracking two things:
The lowest price seen so far (
min_price
)The maximum profit you could make if you sold at the current price
As you walk through the array:
If today’s price is lower than
min_price
, updatemin_price
Otherwise, calculate
price - min_price
and see if it’s your best profit yet
What to watch out for: You can’t sell something before you buy it!
Think of it as keeping an eye out for Black Friday deals — always track the cheapest item so far, and ask: “If I sold today, what’s the best I could do?”
✅ Python Solution:
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
🧵 TL;DR:
📉 Track the lowest price seen so far
💸 Compare each day’s price to that low
⚡ O(n) time, O(1) space, elegant and fast
📉📈 One good trade is all you need