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

MediumGreedyArrayDynamic Programming
Problem
#122
Pattern
Greedy
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

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

Complexity

MeasureComplexity
TimeO(n), where n is the length of the `prices` array
SpaceO(1) auxiliary

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

On a study list

This problem is on Top Interview 150.

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.

Get Stealth Interview