Best Time to Buy and Sell Stock — LeetCode 121 Python Solution

EasyArrayDynamic Programming
Problem
#121
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array nums
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview