码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]123. Best Time to Buy and Sell Stock III

时间:2016-07-01 08:58:35      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

 

 

123. 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保存i之前交易获得的收益。postprofit保存i之后交易获得的收益。

max{preprofit[i]+postprofit[i]}既是最大的可能收益。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int size=prices.size();
        if (size<2)
            return 0;
        int curmin=prices[0],curmax=prices[size-1];
        vector<int> preProfit(size,0);
        vector<int> postProfit(size,0);
        for(int i=1;i<size;i++){
            curmin=min(curmin,prices[i]);
            preProfit[i]=max(preProfit[i-1],prices[i]-curmin);
        }
        for (int j = size-1;j>0; --j){
            curmax=max(curmax,prices[j]);
            postProfit[j]=max(postProfit[j-1],curmax-prices[j]);

        }
        int retProfit=0;
        for(int m=0;m<size;m++){
            if(retProfit<(preProfit[m]+postProfit[m]))
                retProfit=preProfit[m]+postProfit[m];
        }
        return retProfit;
    }
};

 

[leetcode]123. Best Time to Buy and Sell Stock III

标签:

原文地址:http://www.cnblogs.com/LUO77/p/5631768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!