Best Time to Buy and Sell Stock - Problem

You are given an array prices where prices[i] is the price of a given stock on the i-th day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Input & Output

Example 1 — Basic Case
$ Input: prices = [7,1,5,3,6,4]
Output: 5
💡 Note: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Example 2 — No Profit
$ Input: prices = [7,6,4,3,1]
Output: 0
💡 Note: In this case, no transactions are done and the max profit = 0. Prices are continuously decreasing, so no profit can be made.
Example 3 — Small Profit
$ Input: prices = [1,2]
Output: 1
💡 Note: Buy on day 1 (price = 1) and sell on day 2 (price = 2), profit = 2-1 = 1.

Constraints

  • 1 ≤ prices.length ≤ 105
  • 0 ≤ prices[i] ≤ 104

Visualization

Tap to expand
Best Time to Buy and Sell Stock INPUT Stock Prices Over Days 7 5 3 1 BUY SELL 0 1 2 3 4 5 prices array: 7 1 5 3 6 4 Green=Buy day, Red=Sell day Find max profit from one transaction Must buy before selling ALGORITHM STEPS 1 Initialize Variables minPrice = infinity maxProfit = 0 2 Iterate Through Prices For each price in array do steps 3 and 4 3 Update Min Price If price less than minPrice minPrice = price 4 Update Max Profit profit = price - minPrice maxProfit = max(maxProfit, profit) Tracking Progress Day Price MinPrice Profit 0 7 7 0 1 1 1 0 2 5 1 4 4 6 1 5 FINAL RESULT Optimal Transaction BUY Day 1 $1 SELL Day 4 $6 Profit Calculation: $6 - $1 = $5 OK - Maximum Profit! OUTPUT 5 Maximum profit achievable with one transaction Time: O(n) | Space: O(1) Single pass, constant space Key Insight: Track minimum price seen so far as you iterate. At each step, calculate potential profit if selling at current price (current - minPrice). The minimum always comes BEFORE current position, ensuring we buy before we sell. Update maxProfit whenever we find a better deal. TutorialsPoint - Best Time to Buy and Sell Stock | One Pass Tracking Approach
Asked in
Amazon 89 Microsoft 67 Apple 45 Google 43 Facebook 34
892.4K Views
Very High Frequency
~15 min Avg. Time
19.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen