LeetCode 123.

Tags:

package lc_123;

/**
 * @description: time exceeded
 */
public class Solution {
//    public int maxProfit(int[] prices) {
//        if (prices.length < 2) return 0;
//        int max = 0, len = prices.length;
//        for (int i = 1; i <= len - 1; i++){
//            max = Math.max(max, singleTransaction(0, i, prices) + singleTransaction(i, len-1, prices));
//        }
//        return max;
//    }
//    public int singleTransaction(int from, int to, int[] prices){
//        int min = Integer.MAX_VALUE;
//        int max = 0;
//        for (int i = from+1; i <= to; i++){
//            for (int j = i-1; j>=from; j--){
//                min = Math.min(min, prices[j]);
//            }
//            max = Math.max(max, prices[i] - min);
//        }
//        return max;
//    }

    public int maxProfit(int[] prices){
        int buy1 = Integer.MAX_VALUE;
        int buy2 = Integer.MAX_VALUE;
        int sell1 = 0, sell2 = 0;
        for (int price: prices){
            buy1 = Math.min(buy1, price);
            sell1 = Math.max(sell1, price - buy1);
            buy2 = Math.min(buy2, price - sell1);
            sell2 = Math.max(sell2, price - buy2);
        }
        return sell2;
    }
}

Check out the description of this problem at LC 123.