‹ DS&A interview · Socratic
DSA · Arrays · #41

Best Time to Buy and Sell Stock

Module 48 · difficulty 2/5·30:00starts on first keystroke

You are given an array `prices` where `prices[i]` is the price of a given stock on day `i`. 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. Implement `maxProfit(prices)` that returns the maximum profit you can achieve. If no profit is possible, return `0`.

Examples
  • prices = [7,1,5,3,6,4] 5Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5. Buying before the lowest point is not allowed since the sell day must come after the buy day.
  • prices = [7,6,4,3,1] 0Prices only decrease, so no transaction yields a positive profit; return 0.
  • prices = [2,4,1] 2Buy at 2, sell at 4, profit = 2. The later dip to 1 cannot be exploited.
Constraints
  • · 1 <= prices.length <= 10^5
  • · 0 <= prices[i] <= 10^4
  • · Buy day must strictly precede sell day.
Session phases
A · Clarify
B · Approach
C · Complexity
D · Edges
E · Code
F · Tradeoff
G · Score
Phase A — Clarify
Ask questions about input bounds, types, and edge constraints.
Ask the coach clarifying questions about the problem.
When you've covered this phase, advance to the next.