Leetcode-Buy and sell stock
Ref:link Ref:Most consistent ways of dealing with the series of stock problems
The equation for all these problems are:
Base cases:
T[-1][k][0] = 0, T[-1][k][1] = -Infinity
T[i][0][0] = 0, T[i][0][1] = -Infinity
Recurrence relations:
T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i])
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])
See the above link for more details. And below is all related problems.
121.Best Time to Buy and Sell Stock
122.Best Time to Buy and Sell Stock II
123.Best Time to Buy and Sell Stock III
188.Best Time to Buy and Sell Stock IV
309.Best Time to Buy and Sell Stock with Cooldown
714.Best Time to Buy and Sell Stock with Transaction Fee
309. Best Time to Buy and Sell Stock with Cooldown(Medium)
In this problem, we have to buy and sell with cooldown. If we want to buy on the i-th day, we need to make sure we didn’t sell on (i-1)th day.
Therefor, we need to change T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])
to T[i][k][1] = max(T[i-1][k][1], T[i-2][k-1][0] - prices[i])
.
We need to consider about (i-2)th day’s profit. Remember to update the value of previous one.
Time complexity is O(n). Space complexity is O(1). Here is the link.
public int maxProfit(int[] prices) {
if(prices.length<=1)return 0;
int T_ik0 = 0;
int T_ik1 = Integer.MIN_VALUE;
int T_ik2 = 0;
for(int i =0;i<prices.length;i++){
int old = T_ik0;
T_ik0 = Math.max(T_ik0,T_ik1+prices[i]);
T_ik1 = Math.max(T_ik1,T_ik2-prices[i]);
T_ik2 = old;
}
return T_ik0;
}
714. Best Time to Buy and Sell Stock with Transaction Fee (Medium)
In this problem, we need to pay transaction fee. The recurrence relations should be:
T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i] - fee)
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])
Time complexity is O(n). Space complexity is O(1). Here is the link.
public int maxProfit(int[] prices, int fee) {
if(prices.length<=1)return 0;
int T_ik0 = 0;
int T_ik1 = Integer.MIN_VALUE;
for(int price:prices){
T_ik1 = Math.max(T_ik1,T_ik0-price);
T_ik0 = Math.max(T_ik0,T_ik1+price-fee);
}
return T_ik0;
}
123. Best Time to Buy and Sell Stock III (Hard)
In this problem, we can only do two transactions. The recurrence relations are:
T[i][2][0] = max(T[i-1][2][0], T[i-1][2][1] + prices[i])
T[i][2][1] = max(T[i-1][2][1], T[i-1][1][0] - prices[i])
T[i][1][0] = max(T[i-1][1][0], T[i-1][1][1] + prices[i])
T[i][1][1] = max(T[i-1][1][1], -prices[i])
Time complexity is O(n). Space complexity is O(1). Here is the link
public int maxProfit(int[] prices) {
int T_i20 = 0;
int T_i10 = 0;
int T_i21 = Integer.MIN_VALUE;
int T_i11 = Integer.MIN_VALUE;
if(prices.length<=1)return 0;
for(int price:prices){
T_i20 = Math.max(T_i20,T_i21+price);
T_i21 = Math.max(T_i21,T_i10-price);
T_i10 = Math.max(T_i10,T_i11+price);
T_i11 = Math.max(T_i11,-price);
}
return T_i20;
}