首页 > 其他 > 详细

[LeetCode] Best Time to Buy and Sell Stock III

时间:2014-07-13 23:22:32      阅读:362      评论:0      收藏:0      [点我收藏+]

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

 

Solution:

bubuko.com,布布扣
class Solution {
public:
    
int maxProfit(vector<int> &prices) {
        if(prices.size() < 2) return 0;
        int ans = 0;
        int day_num = prices.size();
        int *postMax = new int[day_num + 1], *postBest = new int[day_num + 1];//the max start from i, buy on the day i, the max profit
        postMax[day_num - 1] = 0;
        postBest[day_num - 1] = 0;
        for(int i = day_num - 2;i >= 0; i--)
        {
            postMax[i] = max(postMax[i + 1], prices[i + 1]);
            postBest[i] = max(postBest[i + 1], postMax[i] - prices[i]);
        }
        /*
        cout << "max: ";
        for(int i = 0;i < day_num;i++)
            cout << curMax[i] << " ";
        cout << endl;
        cout << "Best: ";
        for(int i = 0;i < day_num;i++)
            cout << curBest[i] << " ";
        cout << endl;
        */
        //two transactions, once the first sell out at day j, the next best choo        
        //sell on the day i, the best time to buy
        ans = postBest[0];
        int *preBest = new int[day_num + 1], *preMin = new int[day_num + 1];//the max profit of the first transaction.
        preBest[0] = 0;
        preMin[0] = prices[0];
        int tmpProfit = 0;
        for(int i = 1;i < day_num - 2;i++)
        {
            preBest[i] = max(preBest[i - 1], prices[i] - preMin[i - 1]);
            preMin[i] = min(preMin[i - 1], prices[i]);
            tmpProfit = preBest[i] + postBest[i + 1];
            //cout << "temp = " << tmpProfit << endl;
            if(tmpProfit > ans) ans = tmpProfit;
        }

        return ans;
    }
};
View Code

[LeetCode] Best Time to Buy and Sell Stock III,布布扣,bubuko.com

[LeetCode] Best Time to Buy and Sell Stock III

原文:http://www.cnblogs.com/changchengxiao/p/3840438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!