greedy · Problem 1 of 2

Best Time to Buy and Sell Stock

easy
Amazon logoAmazon
Google logoGoogle
Meta logoMeta
Microsoft logoMicrosoft
Apple logoApple
Goldman Sachs logoGoldman Sachs

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.

maxProfit([7, 1, 5, 3, 6, 4]) -> 5
// Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.

maxProfit([7, 6, 4, 3, 1])    -> 0
// Prices strictly decrease, so no profitable transaction is possible.

Your solution

Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.

Running is free — Submit is what records it. Or press ⌘↩

Tests

5 cases, 1 hidden
calltypeexpectedresult
maxProfit([7,1,5,3,6,4])standard profitable case5
maxProfit([7,6,4,3,1])strictly decreasing prices0
maxProfit([1,4])two days profitable3
maxProfit([5])single day no transactions0
withheldhiddenwithheld

Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.

Complexity

target time
O(n)
target space
O(1)

Greedy single-pass scan maintaining running minimum and maximum profit.

Hints

Stuck? Hints open one at a time, each giving a little more away.

3 hints left