Best Time to Buy and Sell Stock – Solution & Complexity
Quick practice for Best Time to Buy and Sell Stock: 3 reasoning beats, no typing
Watch: Best Time to Buy and Sell Stock in one pass
Comparing every pair of days is O(n²). Instead, walk the prices once and remember the cheapest price so far. Each day, selling today earns price − cheapest; keep the best of those. One pass, O(n) time and O(1) space.
Solution Walkthrough
Step 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.
Step 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²).
Step 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.
Step 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.
- Initialize
Step 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.
- The scan preserves the rule that buying happens before selling because