【LeetCode】123. Best Time to Buy and Sell Stock III


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

 

動態規划

使用兩個數組,forw和back。

forw[i]表示從0到i的最優買賣值(低買高賣,為正)。需要一次從左往右遍歷。

back[i]表示從m-1到i的最差買賣值(高買低賣,為負)。需要一次從右往左遍歷。

再對應元素相減:forw[i]-back[i]的最大值即解。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int m = prices.size();
        if(m == 0)
            return 0;
        
        int ret = 0;
        vector<int> forw(m, 0);
        vector<int> back(m, 0);
        
        //forward
        int curMin = prices[0];
        for(int i = 1; i < m; i  ++)
        {
            curMin = min(curMin, prices[i]);
            forw[i] = max(forw[i-1], prices[i]-curMin);
        }
        //backward
        int curMax = prices[m-1];
        for(int i = m-2; i >= 0; i --)
        {
            curMax = max(curMax, prices[i]);
            back[i] = min(back[i+1], prices[i]-curMax);
            
            ret = max(ret, forw[i]-back[i]);
        }
        
        return ret;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM