Best Time to Buy and Sell Stock — LeetCode 121 Python Solution
- Problem
- #121
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array prices where prices[i] is the price of a given stock on the ith 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.
Example
- Input
- prices = [7,1,5,3,6,4]
- Output
- 5
- Explanation
- Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Python solution
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ans, mi = 0, inf
for v in prices:
ans = max(ans, v - mi)
mi = min(mi, v)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array nums |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 121. Best Time to Buy and Sell Stock is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 121. Best Time to Buy and Sell Stock?
- LeetCode 121. Best Time to Buy and Sell Stock is rated Easy on LeetCode.
- What is the time complexity of LeetCode 121. Best Time to Buy and Sell Stock?
- The Python solution on this page runs in O(n), where n is the length of the array nums.
- What is the space complexity of LeetCode 121. Best Time to Buy and Sell Stock?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 121. Best Time to Buy and Sell Stock cover?
- LeetCode 121. Best Time to Buy and Sell Stock is tagged Array and Dynamic Programming on LeetCode.