Best Time to Buy and Sell Stock
FreeSliding windowEasy12 of 75
The problem
Given daily prices, choose one buy day and a later sell day to maximize profit. You may make no transaction, giving profit zero.
Example
[8, 3, 6, 1, 5] → 4
Need a hint?
For a sale today, only the cheapest earlier price matters.
Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.
Notes stay in this browser when storage is available.
Read the solution approach
Track the minimum price seen and the best profit. For each new day, compare today’s price minus that minimum with the best profit, then update the minimum. Initialize best profit to zero so falling prices never force a loss.
Complexity
O(n) time and O(1) extra space.
Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.