- Link: 121. Best Time to Buy and Sell Stock - Easy
- Track: NeetCode150
Question
Restate the problem
- Given an array, where
prices[i]is the stock price on dayi - Choose one day to buy and a later day to sell to maximize profit.
- Return the maximum profit, return
0if no profitable transition exists.
Edge Case
- If prices are decreasing, return
0
| Method | Approach | Time Complexity | Space Complexity |
|---|---|---|---|
| Method 1 ⭐ | Greedy | ||
| Method 2 | Two Pointers |
Method 1 - Greedy
Key idea: Keep the minimum price so far; at each day, treat today as the sell day and update the best profit.
Approach
- Invariant:
min_priceis always the minimum of all prices seen so far. max_profitis always the best achievable profit up to the current day- Iterate through each price:
- Update
min_price - Compute profit if selling today and update
max_profit
- Update
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
min_buy = float("inf")
max_profit = 0
for p in prices:
min_buy = min(min_buy, p)
max_profit = max(max_profit, p - min_buy)
return max_profitMethod 2 - Two Pointers
Approach
- Use two pointers:
left= buy day (the lowest price in the current window)right= sell day (moves forward to scan prices)
- Initialize
left = 0,right = 1,profit = 0 - While
right < n:- If
prices[right] > prices[left], selling onrightis profitable:- update
profit = max(profit, prices[right] - prices[left])
- update
- Otherwise,
prices[right]is a better (lower) buy price:- move
left = rightto start a new window
- move
- Move
right += 1
- If
- Return
profit(remains0if no profitable trade exists)
Complexity
- Time Complexity:
- Space Complexity:
Code
class Solution:
def maxProfit(self, prices: List[int]) -> int:
left = 0 # buy
right = 1 # sell
profit = 0
while right < len(prices):
if prices[right] > prices[left]:
profit = max(profit, prices[right] - prices[left])
else:
left = right
right += 1
return profit