LeetCode 123 Best Time to Buy and Sell Stock III

1.题目
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).
给定一个数组,每个元素分别代表每天的股票价格,要求最多可进行两次交易,求得获取的最大利润和。注意:买入必须在卖出之前,同一时间只能进行一次交易。
2.分析
该题目如果不要求时间复杂度,则可直接通过遍历一边数组,找出所有连续增加的值得最大和最小值的差值,然后在这些差值中找出最大的两个然后求和即为我们的求解结果。但是这种做法时间复杂度为O(n2),显然有很大的优化空间。
由题意分析得出满足动态规划的要求。采用空间换时间方法,以第i天为分界线,计算第i天之前进行一次交易的最大收益preProfit[i],和第i天之后进行一次交易的最大收益postProfit[i],最后遍历一遍,max{preProfit[i] + postProfit[i]} (0≤i≤n-1)就是最大收益。第i天之前和第i天之后进行一次的最大收益求法同Best Time to Buy and Sell Stock I。
code:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length<2){
            return 0;
        }
        int len=prices.length;
        int preProfit[]=new int[len];
        int postProfit[]=new int[len];
        int curMin=prices[0];
        preProfit[0]=0;
        for(int i=1;i<len;i++){
            curMin=Math.min(curMin,prices[i]);
            preProfit[i]=Math.max(preProfit[i-1],prices[i]-curMin);
        }
        postProfit[len-1]=0;
        int curMax=prices[len-1];
        for(int i=len-2;i>=0;i--){
            curMax=Math.max(curMax,prices[i]);
            postProfit[i]=Math.max(postProfit[i+1],curMax-prices[i]);
        }
        int maxProfit=0;
        for(int i=0;i<len;i++){
            maxProfit=Math.max(maxProfit,preProfit[i]+postProfit[i]);
        }
        return maxProfit;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章