Best Time to Buy and Sell Stock

Sliding Window, problem 1 of 7

Best Time to Buy and Sell Stock

Easy

LC #121

arraygreedyrunning minimum

Not attempted yet

prices[i] is a stock's price on day i. You may buy once and sell once, and the sale must be on a later day than the purchase.

Return the largest profit you can make. If every trade would lose money, return 0 (just don't trade).

Example 1

Input: prices = [7,1,5,3,6,4]
Output: 5
Buy at 1 (day 1), sell at 6 (day 4).

Example 2

Input: prices = [7,6,4,3,1]
Output: 0
The price only falls.

Example 3

Input: prices = [2,4,1]
Output: 2
Selling before buying isn't allowed.

Constraints

  • 1 ≤ len(prices) ≤ 10^5
  • 0 ≤ prices[i] ≤ 10^5

Python

Loading draft…

Test results

9 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 6 hidden

Run examples, then submit all tests.