Skip to interview prep
Apexed

6. Best Time to Buy and Sell Stock

EasyArrays & hashing

prices[i] is a stock's price on day i. Choose one day to buy and a later day to sell. Return the maximum profit, or 0 if no profit is possible.

Example 1

Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy at 1, sell at 6

Example 2

Input: prices = [7, 6, 4, 3, 1]
Output: 0

Constraints

  • 1 ≤ prices.length ≤ 10⁵

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Best Time to Buy and Sell Stock — coding interview practice — Apexed