两次交易买入卖出各用buy1,buy2,sell1,sell2表示, sell1表示第一个最大效益,sell2表示第二次交易的最大的效益。buy2与sell1是相关的,最后可能出现全跌的情况,需要判断其与0的大小关系。

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 两次交易所能获得的最大收益
     * @param prices int整型一维数组 股票每一天的价格
     * @return int整型
     */
    public int maxProfit (int[] prices) {
        // write code here
        int buy1,buy2;
        buy1 = -prices[0];
        buy2 = -prices[0];
        int sell1 = 0, sell2 = 0;
        for (int price:prices) {
            buy1 = Math.max(buy1,-price);//以最低价买入
            buy2 = Math.max(buy2,sell1-price);//以最低价买入
            sell1 = Math.max(sell1,buy1+price);
            sell2 = Math.max(sell2,buy2+price);
        }
        int[] res = new int[]{sell1, sell2, 0};
        Arrays.sort(res);
        return res[2];
    }
}