Problems

Best Time to Buy and Sell Stock

easy
easy
arrays
dynamic-programming

Given daily stock prices, return the maximum profit from at most one transaction. The sale must occur after the purchase; return 0 when no profitable trade exists.

Input / output

  • Input: prices: integer[]
  • Output: non-negative integer profit

Examples

  1. [7,1,5,3,6,4] returns 5 by buying at 1 and selling at 6.
  2. [7,6,4,3,1] returns 0.

Constraints

  • 0 <= prices.length <= 100,000
  • 0 <= prices[i] <= 1,000,000

Follow-up How would the state change for unlimited transactions or at most k transactions?

Examples

Example 1

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

Example 2

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

Example 3

Input: prices = [1,2]
Output: 1
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.