You can only sell and buy once 1. mantain a profit and low int
122 II
You can buy and sell many times 1. greedy algo 2. if profitable, add on
public int maxProfit(int[] prices) {
int profit = 0;
for(int i=1; i<prices.length; i++){
if(prices[i] - prices[i-1] > 0){
profit += prices[i] - prices[i-1];
}
}
return profit;
}
123 III
You can only buy and sell twice 1. DP
public int maxProfit(int[] prices) {
int buy1 = - prices[0], buy2 = - prices[0];
int sell1 = 0, sell2 = 0;
for (int i=1; i<prices.length; i++){
// buy1每天都跟新購買比較
buy1 = Math.max(buy1, - prices[i]); // max profit of first buy
sell1 = Math.max(sell1, buy1 + price[i]); // max profit of first sell
buy2 = Math.max(buy2, sell1 - price[i]); // max profit of second buy
sell2 = Math.max(sell2, buy2 + price[i]); // max profit of second sell
}
return sell2;
}
188 IV
You can buy and sell for k times
Hold stock and unhold stock tables
State: 1. hold[i][j]: the max profit in ith day and j transaction with holding stock 2. unhold[i][j]: the max profit in ith day and j transaction without holding stock