[LeetCode] Best Time to Buy and Sell Stock III

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

你可能感兴趣的:(LeetCode)