Best Time to Buy and Sell Stock II

Medium

Topics
ArrayGreedyDynamic Programming

You are given an array prices where prices[i] is the price of a stock on day i. You may buy and sell as many times as you like (but hold at most one share at a time). Return the maximum profit.

Example 1

715364
day with a rise over the previous one
With unlimited transactions there is no need to find peaks and valleys: every upward step can be banked on its own, and the sum of all of them is the same as the sum of the best peak-to-valley runs. Total 7.
Bars are the daily prices, left to right.
Input:  prices = [7,1,5,3,6,4]
Output: 7

Example 2

12345
day with a rise over the previous one
Input:  prices = [1,2,3,4,5]
Output: 4

Constraints

  • 1 <= prices.length <= 3*10^4
  • 0 <= prices[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Unlimited transactions, and you may sell and rebuy on the same day. That freedom makes the problem much easier than it looks, and the reason is worth stating properly.

Any profitable multi-day hold decomposes into consecutive daily gains: buying at day i and selling at day j yields prices[j] - prices[i], which telescopes into the sum of every daily change in between. So a long hold through a rising stretch earns exactly the same as buying and selling each day within it. Since we can skip the negative days entirely, the maximum is simply the sum of every positive daily change.

prices  1  5  3  6
deltas    +4 -2 +3
take the positives: 4 + 3 = 7
which is the same as (5-1) + (6-3)

No state machine, no DP — though the four-state DP from the "at most two transactions" variant also solves this with the transaction cap removed, and that is the answer if a transaction fee is added later.

Approach

  1. Sum prices[i] - prices[i-1] whenever it is positive.

Dry Run

prices = [7,1,5,3,6,4]

7->1   -6   skip
1->5   +4   profit 4
5->3   -2   skip
3->6   +3   profit 7
6->4   -2   skip

answer 7   (buy at 1 sell at 5, buy at 3 sell at 6)

Complexity

  • Time — O(n): one pass.
  • Space — O(1): one accumulator.

Common Pitfalls

  • Trying to identify actual buy and sell days. The sum of positive deltas gives the right total without naming them, and reconstructing the trades is a separate question.
  • Looking for the single largest rise. That solves the one-transaction variant instead.
  • Adding negative deltas, which is equivalent to being forced to hold through a decline.
  • Assuming a transaction fee can be handled by this greedy. It cannot — a fee makes the decomposition invalid, because splitting one long hold into many trades then pays the fee repeatedly, and the problem becomes the state-machine DP.

Full Solution — all languages

class Solution:
    def maxProfit(self, nums):
        profit = 0
        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1]:
                profit += nums[i] - nums[i - 1]
        return profit
SensAI
Beta
Tap the mic to stop voice mode