Best Time to Buy and Sell Stock II

Given an array of daily stock prices, find the maximum profit achievable by completing as many non-overlapping buy-sell transactions as you like.

MediumRecommendedGreedy Array Patterns
Solve This Problem

Video Solution

Video coming soon

We're producing a video walkthrough — check back soon.

Problem Overview

Given an array of daily stock prices, find the maximum profit achievable by completing as many non-overlapping buy-sell transactions as you like.

Why solve this?

The direct sequel to the single-transaction version — the same array, but the constraint changes from once to as many times as you want, and the optimal strategy pivots from tracking a minimum to summing every upward step.

Pattern Recognition

When a problem removes a 'do this only once' restriction and allows unlimited repeats with no cooldown or fee, check whether the optimal answer decomposes into every individual profitable move — that's the greedy signal.

Prerequisites

  • Best Time to Buy and Sell Stock — this problem changes exactly one constraint: unlimited transactions instead of one.

Hints

  1. You're allowed to buy and sell any number of times, as long as you're never holding more than one share at once.
  2. Instead of thinking about isolated buy/sell pairs, look at each single day-to-day price difference.
  3. If tomorrow's price is higher than today's, capturing that gain is never a mistake — sum up every positive day-to-day difference.

Approach

Walk the array once comparing each day to the day before it. Whenever prices[i] > prices[i-1], add that difference to a running profit total — this is equivalent to buying the day before and selling the day of every single upward step, which always matches or beats any coarser buy/sell pairing over the same climb. Days where the price falls or stays flat contribute nothing. No transaction limit needs to be tracked explicitly, because summing every positive step already accounts for as many transactions as the price sequence naturally supports.

Code

Solution.java
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i - 1]) {
                profit += prices[i] - prices[i - 1];
            }
        }
        return profit;
    }
}
Time: O(n)Space: O(1)

Related Problems

Back to Arrays