CodeSpeek

Best Time to Buy And Sell Stock

Easy · Sliding Window

You are given a list of daily stock prices, where each entry is the price on that day. You may buy the stock on exactly one day and sell it on a later day to maximize your profit. Return the maximum profit achievable, or 0 if no positive profit is possible from any such single buy-then-sell transaction.

Examples

Input:  prices = [7,1,5,3,6,4]
Output: 5
Why:    Buy at price 1 and sell at price 6 to get the largest gain of 5.
Input:  prices = [7,6,4,3,1]
Output: 0
Why:    Prices only fall, so no purchase followed by a later sale can produce a positive gain.
Input:  prices = [2,4,1]
Output: 2
Why:    Buy at 2 and sell at 4 for a gain of 2, which beats any other buy/sell pairing here.

Constraints

1 <= prices.length <= 10^5, 0 <= prices[i] <= 10^4

Practise it by voice

Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.

Practise Best Time to Buy And Sell Stock

This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Best Time to Buy And Sell Stock. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.