Buy and Sell Stock
121 I
122 II
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
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
714 With transaction fee
309 With 1 day cool down
Last updated