Easy · Algorithms & Data Structures · Coding · ~10 min · #39
Best Single Round Trip
Given a list of daily prices, return the maximum profit from one buy followed by one later sell. If no profitable trade exists, return 0.
Implement max_profit(prices: list[float]) -> float in time and extra space.
Examples
Input: max_profit([7, 1, 5, 3, 6, 4])
Output: 5
Buy at 1, sell at 6.
Input: max_profit([7, 6, 4, 3, 1])
Output: 0
Prices only fall.
Constraints
- •
1 ≤ len(prices) ≤ 10⁵
- •
Prices are non-negative.
Hints · 0 of 2 shown
Worked solution
Give the problem an honest attempt first, then reveal the full explanation.
Related questions
Concepts
Running minimumSingle-pass algorithms
Relevant for
Quant DeveloperQuant Trader