easyArraySliding WindowSliding Window

Best Time to Buy and Sell Stock

easyTime: O(n)Space: O(1)

Recognize the pattern

best time to buy then sellmaximize profitsingle pass

Brute force idea

A straightforward first read of Best Time to Buy and Sell Stock is this: Check every buy-sell pair. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

A calmer way to see Best Time to Buy and Sell Stock is this: Track minimum price so far, compute profit at each day. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Best Time to Buy and Sell Stock is this: At each price, the best profit is current price minus the minimum seen so far. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

One easy way to drift off course in Best Time to Buy and Sell Stock is this: Trying to find both buy and sell days — you only need to track the running minimum. The fix is usually to return to the meaning of each move, not just the steps themselves.

Sliding Window Pattern