Best Time to Buy and Sell Stock II
Last updated
Was this helpful?
Last updated
Was this helpful?
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
The general idea is to buy stock at valleys (lowest price) and then sell stock at its next peak (highest price). In the below drawing, there are two valleys and two peaks. Since (1) we have to buy stock before selling it and (2) we can not have back-to-back buy or sell trades, thus there are two options of trading stocks.
Option 1: Buy stock at valley[1]
then sell at peak[5]
makes profit A (peak[5] - valley[1])
. Then buy stock at valley [3]
and sell at peak[6]
makes profit B (peak[6] - valley[3])
. So the total profit of this trade option is A + B.
Option 2: Skip the intermediate trades, i.e,, we buy stock at valley[1]
then sell at peak[6]
. In this case, the total profit will be C (peak[6]-valley[1])
.
Based on the graph shown below, A + B > C --> 4 + 3 > 6 (if not, peak[i] and valley[j] won't exist). So in order to maximize the profit, we can buy stock at valleys and then sell stock at peaks.
I've drawn the below illustration to help conceptualize this problem: