Best Time to Buy and Sell Stock II

Find the most money you can make from a stock's daily prices when you may buy and sell as often as you like.

You are given an array prices, where prices[i] is the price of one share of a stock on day i. On each day you may buy a share, sell the share you own, or both. You may own at most one share at a time. Return the largest total profit you can make. If no plan earns anything, the answer is 0.

Example 1
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 7
Explanation: buy at 1 and sell at 5 for a profit of 4, then buy at 3 and sell at 6 for 3 more.
Example 2
Input: prices = [1, 2, 3, 4, 5]
Output: 4
Explanation: buy at 1 and sell at 5.
Example 3
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: the price only falls, so the best plan is not to buy at all.
Solution

The Idea

Imagine you could see a stock's price for every day ahead of time. You can own one share at most, but you may buy and sell as often as you like. How much could you earn?

Take Example 1. On day 0 the price is 7, and on day 1 it drops to 1. Owning the share across that drop would only lose money, so you wait. From day 1 to day 2 the price climbs from 1 to 5, so buying on day 1 and selling on day 2 earns 4. Then the price drops to 3, climbs to 6 and drops to 4. Buying at 3 and selling at 6 earns 3 more, 7 in total.

Could another plan do better? Keeping the share from 5 down to 3 would cost 2. Buying at 1 and selling at 6, the best single trade, earns only 5. Look at the left chart in the picture below.

Left: the prices 7, 1, 5, 3, 6, 4 over days 0 to 5. The two rises, +4 from 1 to 5 and +3 from 3 to 6, add up to 7. Right: the prices 1, 2, 3, 4, 5 climb in four +1 steps, which add up to the same 4 as buying at 1 and selling at 5.

The orange lines show where the price goes up: +4 from day 1 to day 2, and +3 from day 3 to day 4. The grey dashed lines show where it goes down, the stretches when you would rather not own the share. The two trades that earn 7 cover exactly the orange lines.

Now look at the right chart, Example 2. There the best plan is one long trade, buying at 1 and selling at 5, for 4. Yet the climb from 1 to 5 is made of four daily steps of +1, and the steps add up to the whole climb: 1 + 1 + 1 + 1 = 4. Buying on day 0 and selling on day 1, then buying again on day 1 and selling on day 2, and so on, earns the same 4.

So the profit of any plan is just the sum of the daily price changes on the days you own the share. The best plan owns it through every rise and through none of the falls. That means the answer is simply the sum of every rise from one day to the next, and there is no need to decide where each trade starts and ends.

Solution Approach

Turning that idea into code means settling three things: why adding up the rises beats every other plan, which days count as a rise, and what happens with fewer than two prices.

Adding the rises instead of trying every plan

Why not simply try every plan? On each day you either act (buy if you own nothing, sell if you own the share) or wait. Each extra day doubles the number of plans: six days give 64 plans, and 30 days give more than a billion.

Adding the rises needs no search. No plan can earn more than that sum, because a plan only collects the daily changes while it owns the share, and the falls among them only lower its total. And the sum can always be reached: a run of rises, like 1, 2, 3, 4, 5, is one trade from its bottom to its top, and each separate run of rises is a trade of its own.

Taking every gain as soon as it appears, without looking further ahead, is called a greedy approach. It is safe here because a choice today never limits a later one: selling today does not stop you from buying again tomorrow.

Which days count as a rise

What about a day when the price falls or stays the same? A fall would lower the total, so it is skipped. A day with no change adds 0 either way. The check prices[i] > prices[i - 1] lets only the real rises through.

Fewer than two prices

What if the array has one price, or none? Each price change is measured from the day before, so the loop starts at index 1. With one price or none it never runs, and the profit stays 0, which matches the problem: a trade on the same day earns nothing.

Java Solution

The method maxProfit works in these steps:

  1. First, set profit to 0. It holds the sum of the rises found so far.
  2. A loop moves i from 1 to the last index and compares the price on day i, prices[i], with the price the day before, prices[i - 1].
  3. When the price on day i is higher, add the difference prices[i] - prices[i - 1] to profit. Otherwise, add nothing.
  4. When the loop is done, return profit.

The main method runs the three examples, a price that never changes, a single price, an empty array, and [2, 9, 1, 9], where two trades earn more than any single one.

Java
import java.util.Arrays;

public class BestTimeToBuyAndSellStockII {

    public static 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];   // a rise: collect it
            }
        }
        return profit;
    }

    public static void main(String[] args) {
        int[][] tests = {
            {7, 1, 5, 3, 6, 4},
            {1, 2, 3, 4, 5},
            {7, 6, 4, 3, 1},
            {3, 3, 3},
            {5},
            {},
            {2, 9, 1, 9}
        };
        for (int[] prices : tests) {
            System.out.println(Arrays.toString(prices) + " -> " + maxProfit(prices));
        }
    }
}

Running it prints:

Output
[7, 1, 5, 3, 6, 4] -> 7
[1, 2, 3, 4, 5] -> 4
[7, 6, 4, 3, 1] -> 0
[3, 3, 3] -> 0
[5] -> 0
[] -> 0
[2, 9, 1, 9] -> 15

Look at the first line: [7, 1, 5, 3, 6, 4] gives 7, the +4 and +3 from the left chart. [1, 2, 3, 4, 5] gives 4 from its four steps of +1. The prices in [7, 6, 4, 3, 1] only fall, so nothing is added and the best plan is never to buy.

The next three lines all print 0. In [3, 3, 3] the price never changes, so the check never passes. For [5] and the empty array the loop does not run at all.

The last line, 15, is two trades: buy at 2 and sell at 9 for 7, then buy at 1 and sell at 9 for 8. With only one trade allowed, the best you could do is 8, by buying at 1 and selling at 9. So looking for the largest gap between a low price and a later high one, which solves the one-trade version of the problem, does not answer this one.

The original implementation, BestTimeToBuyAndSellStockII.java, is on GitHub.

Complexity

The method looks at each pair of neighbouring days once and keeps a single running total.

  • Time: O(n), where n is the number of prices. The loop runs n - 1 times, and each step is one comparison and at most one addition.
  • Space: O(1). Only profit and the loop index are stored, however long prices is. The method neither copies the array nor keeps a list of trades.

When only one trade is allowed, see Best Time to Buy and Sell Stock.