MediumArrayDynamic ProgrammingGreedyUpdated Sep 2026

122. Best Time to Buy and Sell Stock II

Asked at Meta, Apple, Oracle

Difficulty

Medium

Time

O(n)

Space

O(1)

Pattern

Array

Companies

3

Problem

You get an array prices, where prices[i] is the stock price on day i. You may buy and sell as many times as you want, but you can hold at most one share at any moment. So you must sell before you buy again.

Return the maximum total profit you can make. If no trade can earn money, return 0.

Because transactions are unlimited, every upward move is worth taking. If the price rises from day i to day i+1, you can buy on day i and sell on day i+1 and keep that gain. Adding up all such positive differences gives the best possible answer.

Pick the profitable up-moves

prices+4+3715364012345Buy at 1, sell at 5 (+4). Buy at 3, sell at 6 (+3).Total 7.
Each green arrow is a rise we can capture by buying the day before and selling on the rise.

Constraints

  • ●1 <= prices.length <= 3 * 10^4
  • ●0 <= prices[i] <= 10^4

Examples

Example 1
Inputprices = [7,1,5,3,6,4]
Output7
WhyBuy at 1 and sell at 5 for a gain of 4. Then buy at 3 and sell at 6 for a gain of 3. Total is 4 + 3 = 7.
Example 2
Inputprices = [1,2,3,4,5]
Output4
WhyThe price only goes up. Buying at 1 and selling at 5 gives 4. Buying and selling each day also gives 1+1+1+1 = 4, the same result.
Example 3
Inputprices = [7,6,4,3,1]
Output0
WhyThe price only falls, so any trade loses money. The best choice is to never buy, giving 0.

Asked At

3 companies

How to Think About It

1

Greedy insight: whenever the price goes up from day i to day i+1, you capture that gain. Buy on day i, sell on day i+1. The total profit is the sum of all positive price differences. This works because you can hold only one share at a time.

2

Why greedy works here: you can make unlimited transactions. If prices go [1,5,10], buying at 1 and selling at 10 gives 9. But buying at 1, selling at 5 (gain 4), then buying at 5, selling at 10 (gain 5) also gives 9. The greedy approach of capturing every up-move is equivalent and simpler.

3

DP approach: dp[i][0] = max profit on day i holding no stock, dp[i][1] = max profit on day i holding stock. Transitions: dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]), dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]). Final answer: dp[n-1][0].

4

Complexity: greedy is O(n) time, O(1) space. DP is O(n) time, O(1) space (only need previous day). Both are equally efficient here.

Optimal Approach

Greedy: iterate through prices from index 1 to n-1. If prices[i] > prices[i-1], add the difference to total profit. This captures every profitable upswing.

Walkthrough with prices = [7,1,5,3,6,4]:

  • i=1: 1 < 7. Skip.
  • i=2: 5 > 1. Profit += 4. Total = 4.
  • i=3: 3 < 5. Skip.
  • i=4: 6 > 3. Profit += 3. Total = 7.
  • i=5: 4 < 6. Skip.
  • Result: 7

The key insight: buying at 1 and selling at 5, then buying at 3 and selling at 6 gives the same profit as buying at 1 and selling at 6, because you would have missed the dip at 3.

Time: O(n). Space: O(1).

Sum every positive day-to-day change

prices715364012345i-1iStep 1 — compare 1 and 5. 5 > 1, so add 4. Profit = 4.prices715364012345i-1iStep 2 — compare 3 and 6. 6 > 3, so add 3. Profit = 7.if prices[i] > prices[i-1]: profit += prices[i] - prices[i-1]
We only add a difference when today's price is higher than yesterday's.
ComplexityTime O(n)Space O(1)We scan the array once and keep only a running profit total, so no extra memory is needed.

What Trips People Up in Real Interviews

1

Confusing with Stock I where you can only make one transaction. In Stock II, you can make unlimited transactions. The greedy approach of summing all positive differences is specific to this unlimited-transaction variant.

2

Trying to find the single global minimum and maximum. That only works for one transaction. For multiple transactions, you need to capture every local upswing.

3

Overcomplicating with DP when greedy suffices. The DP solution is correct but unnecessary here. Mention both approaches and explain why greedy is simpler and equally efficient.

4

Forgetting that you must sell before buying again. You cannot hold multiple shares simultaneously. The greedy approach naturally handles this by buying and selling on consecutive days.

5

Not handling edge cases: all decreasing prices (profit = 0), single element array (profit = 0), all equal prices (profit = 0). These are valid inputs that should return 0.

Solution Code

O(n) time
def maxProfit(prices):
    profit = 0
    for i in range(1, len(prices)):
        if prices[i] > prices[i - 1]:
            profit += prices[i] - prices[i - 1]
    return profit

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

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

Given an array of prices where prices[i] is the price of a stock on the ith day, maximize your profit by completing as many transactions as you like. You must sell the stock before buying again. This problem tests greedy reasoning about cumulative gains.

How do you solve Best Time to Buy and Sell Stock II?

The optimal approach runs in O(n) time and O(1) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Best Time to Buy and Sell Stock II?

Best Time to Buy and Sell Stock II is asked at Meta, Apple, Oracle. It is a medium difficulty problem.

What are common mistakes on Best Time to Buy and Sell Stock II?
  • Confusing with Stock I where you can only make one transaction. In Stock II, you can make unlimited transactions. The greedy approach of summing all positive differences is specific to this unlimited-transaction variant.
  • Trying to find the single global minimum and maximum. That only works for one transaction. For multiple transactions, you need to capture every local upswing.
  • Overcomplicating with DP when greedy suffices. The DP solution is correct but unnecessary here. Mention both approaches and explain why greedy is simpler and equally efficient.
  • Forgetting that you must sell before buying again. You cannot hold multiple shares simultaneously. The greedy approach naturally handles this by buying and selling on consecutive days.
  • Not handling edge cases: all decreasing prices (profit = 0), single element array (profit = 0), all equal prices (profit = 0). These are valid inputs that should return 0.