首先申明一下,这个思路并不是我想出来的,只是在LeetCode上看到有人这样解,觉得这个思路很不错,所以写下来作为分享和记录。
1.方法1
从题目中可以看出,不管哪一天,都只能是 buy 或者 sell 或者 cooldown(rest) 三种状态中的一种,而根据题目的约束条件,我们可以画出下图所示的状态图:
由此图我们可以得到:
s0[i] = max(s0[i - 1], s2[i - 1])
s1[i] = max(s0[i - 1] - prices[i], s1[i - 1])
s2[i] = s1[i - 1] + prices[i]
其中s0,s1,s2分别表示三种状态下的最大利润值。
值得注意的是这里的s0,s1和s2不是单纯的buy,sell, rest,而应该是
s0 —— sell后rest或者rest后rest
s1 —— rest后的buy或者buy后的rest
s2 —— rest后的sell
还有一点要注意的就是,我们一定是最后一天卖出或者最后一天冻结利润最大。
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int n = prices.length;
int[] s0 = new int[n]; //reset
int[] s1 = new int[n]; //after buy
int[] s2 = new int[n];// after sell
s1[0] = -prices[0];
s2[0] = Integer.MIN_VALUE;
for(int i = 1; i < n; i++){
s0[i] = Math.max(s0[i-1], s2[i-1]);
s1[i] = Math.max(s0[i-1] - prices[i], s1[i-1]);
s2[i] = s1[i-1] + prices[i];
}
return Math.max(s0[n-1], s2[n-1]);
}
}
2.方法2:
- buy[i]表示在第i天之前最后一个操作是买,此时的最大收益。
- sell[i]表示在第i天之前最后一个操作是卖,此时的最大收益。
- cooldown[i]表示在第i填之前最后一个操作是冷冻期,此时的最大收益。
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int buy[]=new int[prices.length];
int sell[]=new int[prices.length];
int cooldown[]=new int[prices.length];
buy[0]=-prices[0];
sell[0]=0;
cooldown[0]=0;
for(int i=1;i<prices.length;i++){
cooldown[i]=sell[i-1];
sell[i]=Math.max(sell[i-1],buy[i-1]+prices[i]);
buy[i]=Math.max(buy[i-1],cooldown[i-1]-prices[i]);
}
return Math.max(sell[prices.length-1],buy[prices.length-1]);
}
}
方法3:
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int[] sdp = new int[prices.length];
int[] bdp = new int[prices.length];
sdp[0] = 0;
bdp[0] = -prices[0];
for (int i = 1;i < prices.length ;i++ ) {
sdp[i] = Math.max(sdp[i-1],bdp[i-1] + prices[i]);
if(i >= 2) {
bdp[i] = Math.max(bdp[i-1],sdp[i-2] - prices[i]);
} else {
bdp[i] = Math.max(bdp[i-1],-prices[i]);
}
}
return sdp[prices.length - 1];
}
}