LeetCode: Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() == 0) return 0;
        int maxProfit = 0;
        int maxp1 = 0;
        int maxp2 = 0;
        int minp1 = prices[0];
        int minp2 = INT_MAX;
        for(int i = 1;i < prices.size();i++){
            int diff1 = prices[i] - minp1;
            if(diff1 < 0){
                minp1 = prices[i]; 
            }else if(diff1 > maxp1){
                maxp1 = diff1;
            }
            
            if(i < prices.size() - 1){
                for(int j = i; j < prices.size();j++){
                    int diff2 = prices[j] - minp2;
                    if(diff2 < 0){
                        minp2 = prices[j];
                    }else if(diff2 > maxp2){
                        maxp2 = diff2;
                    }
                }
            }else{
                maxp2 = 0;
            }
            maxProfit = (maxp1 + maxp2) > maxProfit ? maxp1 + maxp2:maxProfit;
        }
        return maxProfit;
    }
};

Submission Result: Time Limit Exceeded 

在大测试数据面前,还是过不了。

 another solution googled can be accepted by the LeetCode 

public class Solution {
    public int maxProfit(int[] prices) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int min = Integer.MAX_VALUE, max=Integer.MIN_VALUE;
        int [] forward = new int[prices.length], 
               backward = new int[prices.length];
        
        for(int i=0;i<prices.length;i++){
            if(prices[i]>min){
                forward[i]=Math.max(prices[i]-min,forward[i-1]);
            }else{
                if(i>0) forward[i]=forward[i-1];
            }
            min=Math.min(prices[i],min);
            
            if(prices[prices.length-1-i]<max){
                backward[prices.length-1-i]=Math.max(max-prices[prices.length-1-i],backward[prices.length-i]);
            }else{
               if(i>0) backward[prices.length-1-i]=backward[prices.length-i];
            }
            max=Math.max(prices[prices.length-1-i],max);
        }
        
        int res = 0;
        
        for(int i=0;i<prices.length;i++){
            res=Math.max(forward[i]+backward[i],res);
        }
        return res;
    }
}
 
原文地址:https://www.cnblogs.com/yeek/p/3578619.html