MediumNo. 0122

Best Time to Buy and Sell Stock II — LeetCode 122 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Dynamic Programming
On a study list
Top Interview 150
Reading time
2 min

The problem

You are given an integer array prices where prices[i] is the price of a given stock on the ith day. On each day, you may decide to buy and/or sell the stock.

Example

Input
prices = [7,1,5,3,6,4]
Output
7
Explanation
Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.

Python solution

PythonSolution
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        return sum(max(0, b - a) for a, b in pairwise(prices))

Complexity

Time
O(n)where n is the length of the `prices` array
Space · auxiliary
O(1)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 122. Best Time to Buy and Sell Stock II is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0121Best Time to Buy and Sell StockEasy
0045Jump Game IIMedium
0055Jump GameMedium
0376Wiggle SubsequenceMedium
0435Non-overlapping IntervalsMedium
0646Maximum Length of Pair ChainMedium

Frequently asked questions

How hard is LeetCode 122. Best Time to Buy and Sell Stock II?

LeetCode 122. Best Time to Buy and Sell Stock II is rated Medium on LeetCode.

What is the time complexity of LeetCode 122. Best Time to Buy and Sell Stock II?

The Python solution on this page runs in O(n), where n is the length of the `prices` array.

What is the space complexity of LeetCode 122. Best Time to Buy and Sell Stock II?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 122. Best Time to Buy and Sell Stock II cover?

LeetCode 122. Best Time to Buy and Sell Stock II is tagged Greedy, 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.

Free to download. Check it runs on your machine, then pick a plan.