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).

解:

最多进行两次交易,直接按对I的解法,创建两个数组:

profit[i]表示0-i进行一次交易的最大利润

seprofit[i]表示i-(len-1)进行一次交易的最大利润

分别求出两个数组,则可求出以i为分割点进行两次交易的最大利润,求其最大者与进行一次交易的最大利润比较则可得出结果。

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length ==0 || prices.length==1)
            return 0;
        //计算数组profit[]
        int min = prices[0];
        int len = prices.length;
        int[] profit = new int[len];
        profit[0] = 0;
        for(int i = 1; i<len; i++){
            if(prices[i]-min > profit[i-1])
                profit[i] = prices[i]-min;
            else
                profit[i] = profit[i-1];
            if(prices[i] < min) 
                min = prices[i];
        }
        if(len <= 3)
            return profit[len-1];
        
        //计算数组seProfit[]
        int[] seProfit = new int[len];
        seProfit[len-1] = 0;
        int max = prices[len-1];
        for(int i = len-2; i >= 0; i--){
            if(max-prices[i] > seProfit[i+1])
                seProfit[i] = max - prices[i];
            else
                seProfit[i] = seProfit[i+1];
            if(prices[i] > max)
                max = prices[i];
        }
        
        //计算以i为分割点两次交易的最大利润
        int maxProfit = 0;
        for(int i = 0; i<len-1; i++)
            maxProfit = Math.max(profit[i]+seProfit[i+1], maxProfit);
        
        //比较进行一次交易和两次交易的最大利润
        if(maxProfit < profit[len-1])
            maxProfit = profit[len-1];
        return maxProfit;
    }
}

 

你可能感兴趣的:(time)