Best Time to Buy and Sell Stock
Easy · Sliding Window · Array · Dynamic Programming · Greedy
Problem
prices[i] is the price of a stock on day i. Choose one day to buy and a later day to sell, and return the largest profit you can make. If no profit is possible, return 0.
Examples
Input: prices = [7,1,5,3,6,4] Output: 5
Buy on day 1 at 1, sell on day 4 at 6.
Input: prices = [7,6,4,3,1] Output: 0
Prices only fall — never buy.
Constraints
- 1 <= len(prices) <= 10^5
- 0 <= prices[i] <= 10^4
Approaches
- Brute force — every buy/sell pair — time O(n²), space O(1)
Related problems
Start free on Cariara · Coding problems · System design studio