O13
Best Time to Buy and Sell Stock
Problem Statement & Objective
You are given an array prices where prices[i] is the price of a given stock on the i-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve. If no profit can be achieved, return 0.
Function Signature (Python)
max_profit(prices: list[int]) -> intInput & Output Contract
Output Rule:Maximum profit integer. If all prices decrease, returns 0.
System Constraints
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4Example Execution Walkthrough
prices = [7, 1, 5, 3, 6, 4]
buy at 1 (day 2), sell at 6 (day 5), profit = 6 - 1 = 5Example Test Scenarios (3)
Example 1
Input:
[[7,1,5,3,6,4]]Expected Output:
5Example 2: Sürekli Düşen
Input:
[[7,6,4,3,1]]Expected Output:
0Example 3: Geç Dip
Input:
[[2,4,1]]Expected Output:
2