Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
public int maxProfit(int k, int[] prices) {
int[] buy = new int[k + 1], sell = new int[k + 1];
Arrays.fill(buy, Integer.MIN_VALUE);
for (int price : prices) {
for (int i = 1; i <= k; i++) {
buy[i] = Math.max(buy[i], sell[i - 1] - price);
sell[i] = Math.max(sell[i], buy[i] + price);
}
}
return sell[k];
}
Question 1)
I understand most of the solution but I'm a bit confused about the sell[i]
state. For example, when we buy a stock in buy[i]
, it is calculated by sell[i - 1] - price
which means max profit of sell from the previous day minus the cost of buying the stock today.
However, when we buy a stock in sell[i], it is buy[i] + price
instead of buy[i-1]
. If we want sell today, shouldn't it be max profit of buy from yesterday + today's price? So wondering why there is a lack of + 1 when calculating sell[i]
.
Question 2)
Instead of buying or selling we can also choose to hold and do nothing where this is expressed as buy[i]/sell[i]. However, if we don't do anything today, shouldn't the number be a duplicate from the previous day? buy[i+1]/sell[i+1]
. Just wondering why it's buy[i] and not buy[i-1] since in other stock problems, when you choose to do nothing, you grab the value from the previous day.