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 pricesprices[i]i
Example 1
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
Output: 4
Explanation: buy at 1 and sell at 5.
Example 3
Output: 0
Explanation: the price only falls, so the best plan is not to buy at all.
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.
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]
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
- First, set
to 0. It holds the sum of the rises found so far.profit - A loop moves
from 1 to the last index and compares the price on dayi ,i , with the price the day before,prices[i] .prices[i - 1] - When the price on day
is higher, add the differencei toprices[i] - prices[i - 1] . Otherwise, add nothing.profit - When the loop is done, return
.profit
The main[2, 9, 1, 9]
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:
[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][1, 2, 3, 4, 5][7, 6, 4, 3, 1]
The next three lines all print 0. In [3, 3, 3][5]
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,
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
and the loop index are stored, however longprofit is. The method neither copies the array nor keeps a list of trades.prices
When only one trade is allowed, see