O13

Best Time to Buy and Sell Stock

Junior Level Candidate
Target Time: 15 - 20 Minutes
Type: NUMERIC

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]) -> int

Input & Output Contract

Output Rule:Maximum profit integer. If all prices decrease, returns 0.

System Constraints

1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4

Example Execution Walkthrough

prices = [7, 1, 5, 3, 6, 4]
buy at 1 (day 2), sell at 6 (day 5), profit = 6 - 1 = 5

Example Test Scenarios (3)

Example 1
Input:[[7,1,5,3,6,4]]
Expected Output:5
Example 2: Sürekli Düşen
Input:[[7,6,4,3,1]]
Expected Output:0
Example 3: Geç Dip
Input:[[2,4,1]]
Expected Output:2
Loading Python Editor...
Input Parameters
[
  [
    7,
    1,
    5,
    3,
    6,
    4
  ]
]
Expected Output
5