Tensorum
LeetCode 122 · Jump / Reachability

Best Time to Buy and Sell Stock II

LeetCode 122 · Medium · solution, intuition & step-by-step walkthrough

Sum of all positive deltas = best profit with unlimited trades.

MediumArrayDynamic ProgrammingGreedy
0 msruntime · beats 100%
20.2 MBmemory · beats 65%
1approach
11accepted runs · last 26 May 2026

This is how I solved Best Time to Buy and Sell Stock II (LeetCode 122), a medium problem from the Jump / Reachability pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

With unlimited transactions, any rise from one day to the next is money you can collect. A long climb from 1 to 5 is the same as collecting every small daily step on the way up, so just add up every positive day-to-day difference.

Approach

  1. 1

    Compare each day with the day before.

  2. 2

    If today is higher, add the gain to the profit.

  3. 3

    Ignore falling days — you'd simply not hold stock across them.

How I solved it

Greedy deltasPythonO(n) time · O(1) space
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1,len(prices)):
            if prices[i]>prices[i-1]:
                profit+=prices[i]-prices[i-1]
        return profit
Loading the step-through…

Best Time to Buy and Sell Stock II — FAQ

What is the intuition behind Best Time to Buy and Sell Stock II?

With unlimited transactions, any rise from one day to the next is money you can collect. A long climb from 1 to 5 is the same as collecting every small daily step on the way up, so just add up every positive day-to-day difference.

How do you solve Best Time to Buy and Sell Stock II (LeetCode 122)?

1. Compare each day with the day before. 2. If today is higher, add the gain to the profit. 3. Ignore falling days — you'd simply not hold stock across them.

What is the time and space complexity of Best Time to Buy and Sell Stock II?

Time: O(n). Space: O(1). (Accepted approach: Greedy deltas.)

What are common mistakes in Best Time to Buy and Sell Stock II?

This greedy only works because transactions are unlimited and free — fees or cooldowns need the DP versions.