[LeetCode] Best Time to Buy and Sell Stock III

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   strong   

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:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.