Arrays Easy
Best Time to Buy and Sell Stock: Solution and Approach
prices[i] is a stock's price on day i. Buy on one day and sell on a later day. Return the maximum profit, or 0 if no profit is possible.
Similar questions reported in: TCS, Accenture, Amazon
Example
- Input:
- prices = [7, 1, 5, 3, 6, 4]
- Output:
- 5 (buy at 1, sell at 6)
Brute force first
Try every buy day with every later sell day. This is O(n²).
The better idea
The best sale on day i uses the lowest price seen before day i. Keep a running minimum and the best profit so far in a single pass.
Steps
- Set minPrice to a very large value and best to 0.
- For each price: update minPrice = min(minPrice, price).
- Update best = max(best, price - minPrice).
- Return best.
Code
def max_profit(prices):
min_price = float("inf")
best = 0
for p in prices:
min_price = min(min_price, p)
best = max(best, p - min_price)
return bestpublic int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int best = 0;
for (int p : prices) {
minPrice = Math.min(minPrice, p);
best = Math.max(best, p - minPrice);
}
return best;
}Complexity
Time: O(n)
Space: O(1)
Edge cases to test
- Prices that only fall, such as [7, 6, 4]: the answer is 0.
- A single day: the answer is 0.
Interview follow-up: If you can buy and sell many times, add every positive day-to-day difference.
Solved it? Pick the next problem
Do one more problem from the same pattern today, so the idea sticks.