Best Time to Buy and Sell Stock – Solution & Complexity
1. Understand the Goal
- You need choose one day to buy and a later day to sell.
- Profit is
sell_price - buy_price. - If every later price is lower, the best valid answer is
0because you can skip the trade.
2. Consider the Brute Force Idea
- A direct solution checks every possible buy day with every later sell day.
- This finds the correct answer, but it repeats a lot of work.
- With two nested loops, the time complexity is O(n²).
3. Track the Cheapest Buy Price
- When scanning prices from left to right, the best buy day before today is simply the lowest price seen so far.
- For each current price, calculate the profit from selling today after buying at that lowest earlier price.
- Then update the best profit if today gives a better one.
4. Build the One-Pass Loop
- Initialize
min_priceto a very large value andbestto0. - For each price, first update the minimum price seen so far.
- Then compare the current possible profit against the best answer.
5. Final Solution and Complexity
- The scan preserves the rule that buying happens before selling because
min_priceonly comes from days already visited. - Time complexity is O(n) because each price is processed once.
- Space complexity is O(1) because only two variables are stored.