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

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…