Browse curriculum

Best Time to Buy and Sell Stock II

Maximise profit with unlimited stock transactions greedily: add every day-to-day price rise, since any climb is the sum of its daily gains.

Problem Understanding

Best Time to Buy and Sell Stock II: prices[i] is a stock's price on day i. You may buy and sell as many times as you like, holding at most one share at a time (you can sell and buy again on the same day). Return the maximum profit.

Example: [7, 1, 5, 3, 6, 4] returns 7: buy at 1, sell at 5 (+4), buy at 3, sell at 6 (+3).

The Intuition: Collect Every Rise

Draw the prices as a line. Every upward segment is profit you could have made; every downward segment is a loss you could have avoided by not holding. With unlimited trades, you take all of the first and none of the second.

A long climb from 1 to 5 is the same as the daily rises 1→2, 2→3, 3→4, 4→5 added together, so there is no need to find peaks and valleys. That is the whole greedy algorithm:

  • If today's price is higher than yesterday's, add the difference.
  • Otherwise add nothing.

With only one transaction allowed, the problem becomes Best Time to Buy and Sell Stock, where you track the lowest price seen so far instead.

Interactive Walkthrough

Each day's price is a bar. Today is compared with yesterday, and the days that bracket a collected rise turn green; the buy → sell pairs are listed beside the figure. Try Zigzag to see three separate trades.

Dry Run Table

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

Day Yesterday → today Difference Profit
1 7 → 1 −6 0
2 1 → 5 +4 4
3 5 → 3 −2 4
4 3 → 6 +3 7
5 6 → 4 −2 7

Answer: 7.

The Solution Template

One pass, adding each positive day-to-day difference.

Best Time to Buy and Sell Stock II Code
1var maxProfit = function(prices) {
2 let profit = 0;
3 for (let i = 1; i < prices.length; i++) {
4 if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1];
5 }
6 return profit;
7};

Edge Cases & Common Mistakes

  • One day: no trade is possible; the loop does not run and the profit is 0.
  • Prices only fall: every difference is negative or zero; the answer is 0, never negative.
  • One long climb: daily rises add up to exactly last − first, the same as a single trade.
  • Equal neighbours: a difference of 0 adds nothing; use > not ≥ for clarity.
  • Searching for peaks and valleys: works, but the daily-difference sum is simpler and has no off-by-one traps.

Summary

With unlimited transactions, the maximum profit is the sum of every positive day-to-day price difference: each rise is a buy-yesterday, sell-today trade, and any longer trade is just several of these added up. O(n) time and O(1) space. Add a one-day wait after each sale and greedy no longer works: see Stock with Cooldown.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start with zero profit

    Set profit = 0.

  2. Compare each day with the day before

    For each i from 1, if prices[i] > prices[i − 1], add the difference to profit.

  3. Return the profit

    The sum of all daily rises is the maximum profit.

Frequently asked questions

Why does adding every daily rise give the maximum profit?

Any trade from day a to day b earns prices[b] − prices[a], which equals the sum of the daily differences in between. Adding only the positive differences is at least as good as any set of non-overlapping trades, and it is achievable: buy before each rise and sell after it, since selling and buying again on the same day is allowed.


How is Stock II different from Best Time to Buy and Sell Stock?

Stock I allows a single transaction, so you track the lowest price so far and the best single sale. Stock II allows as many transactions as you like, so every rise can be captured and the answer is the sum of the positive differences.


Is there a dynamic programming solution?

Yes: keep two states, cash (not holding) and hold (holding a share). Each day, cash = max(cash, hold + price) and hold = max(hold, cash − price). It gives the same answer and extends to variants with fees or cooldowns.

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description