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

思路:动态规划

思路就是分成两个数组preprofit和postprofit,分别表示从最开始到第i天的最大收益以及从第i天到最后一天的最大收益,第一个只需要判断最小值,判断一个profit,后面的是判断最大值,每次也要比较最大profit。

做这种题目的确有收获,难得的是第四道题目。


代码:

class Solution {
public:
//http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html
//https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
    int maxProfit(vector<int>& prices) {
        if(prices.size()<2){
            return 0;
        }
        int n=prices.size();
        vector<int> preProfit(n,0);
        vector<int> postProfit(n,0);
        
        //从前往后
        int minPrice=prices[0];
        for(int i=1;i<=prices.size()-1;i++){
            minPrice=min(minPrice,prices[i]);
            preProfit[i]=max(preProfit[i-1],prices[i]-minPrice);
        }
        //从后往前
        int maxPrice=prices[n-1];
        for(int i=n-2;i>=0;i--){
            maxPrice=max(maxPrice,prices[i]);
            postProfit[i]=max(postProfit[i+1],maxPrice-prices[i]);
        }
        
        int maxProfit=0;
        for(int i=0;i<=preProfit.size()-1;i++){
            maxProfit=max(maxProfit,postProfit[i]+preProfit[i]);
        }
        
        return maxProfit;
    }
};


posted @ 2015-10-12 08:08  JSRGFJZ6  阅读(102)  评论(0编辑  收藏  举报