You are given an array of prices where prices[i] is the price of a stock on day i. You want to maximize profit by choosing a single day to buy and a single day to sell in the future. Return the maximum profit, or 0 if no profit is possible.
For example, given prices = [7, 1, 5, 3, 6, 4], the maximum profit is 5 (buy on day 2 at price 1, sell on day 5 at price 6).
Explain your approach to solving this problem and state the time and space complexity.
How to approach it
- Hint 1
Think about tracking the minimum price seen so far as you scan from left to right.
- Hint 2
At each day, the potential profit is the current price minus the minimum price so far. Track the maximum of these profits.
- Hint 3
One pass through the array: maintain minPrice and maxProfit. For each price, update minPrice = min(minPrice, price) and maxProfit = max(maxProfit, price - minPrice).
Ready to answer it out loud?
Record your answer in 1:00 and Preptile scores it 1–10 with specifics — what landed, what you skipped, and what to say next time.
Practising needs an invite code. Join the waitlist and we’ll send you one.