123 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III

假设你有一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来找到最大的利润。你最多可以完成两笔交易。
注意:
你不可同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
详见:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/

Java实现:

class Solution {
    public int maxProfit(int[] prices) {  
        int n=prices.length;
        if(prices == null || n <= 1){  
            return 0;  
        }  
        int maxProfit = 0; 
        
        int min = prices[0];  
        int forward[] = new int[n]; 
        for(int i=1;i<n;i++){
            min=Math.min(min,prices[i]);
            forward[i]=Math.max(forward[i-1],prices[i]-min);
        }
        
        int max = prices[n-1];  
        int back[] = new int[n];  
        for(int i = n-2; i >= 0; i--){
            max = Math.max(prices[i],max);
            back[i] = Math.max(max-prices[i],back[i+1]);
        }  
        
        for(int i = 0; i < n; i++){  
            maxProfit = Math.max(maxProfit,forward[i] + back[i]);
        }  
        
        return maxProfit;  
    }
}

参考:https://www.cnblogs.com/springfor/p/3877068.html

原文地址:https://www.cnblogs.com/xidian2014/p/8722816.html