大致思路:最大利润,说白了就是最低价格买,最高价格卖,这样我们就直接用4个变量分别记录最低的购买价格,最高第一次出售后的收益(第一次出售价格-第一次购买价格),最高第二次购买后剩余的收益(第一次出售后的收益-第二次购买购买价格),最高第二次出售后的收益(第二次出售价格+第二次购买后的剩余收益),最后返回最高第二次出售后的收益即可。
public int maxProfit (int[] prices) {
// write code here
int buy1 = Integer.MIN_VALUE,sell1 = 0,buy2 = Integer.MIN_VALUE,sell2=0;
for(int i = 0;i<prices.length;i++){
buy1 = Math.max(-prices[i],buy1);
sell1 = Math.max(sell1,prices[i]+buy1);
buy2 = Math.max(buy2,sell1-prices[i]);
sell2 = Math.max(sell2,buy2+prices[i]);
}
return sell2;
}