Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Best Time to Buy and Sell Stock

Greedyeasy

Implement `maxProfit(prices)` returning the maximum profit from one buy followed by one later sell, or `0` if no profit is possible.

Sample tests

Input: maxProfit([7,1,5,3,6,4])
Output: 5
Input: maxProfit([7,6,4,3,1])
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Selling before buying; the buy must come first in time.

Learning resources

  • Wikipedia: Greedy algorithm
Approach & explanation (try first)

A single pass tracking the running minimum gives the best profit in O(n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.