[leetcode]Best Time to Buy and Sell Stock III


 

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
/*
解釋:
首先,因為能買2次(第一次的賣可以和第二次的買在同一時間),但第二次的買不能在第一次的賣左邊。
所以維護2個表,f1和f2,size都和prices一樣大。
意義:
f1[i]表示 -- 截止到i下標為止,左邊所做交易能夠達到最大profit;
f2[i]表示 -- 截止到i下標為止,右邊所做交易能夠達到最大profit;
那么,對於f1 + f2,尋求最大即可。
*/
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int size = prices.size();
        if (size == 0)
            return 0;

        vector<int> f1(size);
        vector<int> f2(size);

        int minV = prices[0];
        for (int i = 1; i < size; i++){
            minV = std::min(minV, prices[i]);
            f1[i] = std::max(f1[i-1], prices[i] - minV);
        }

        int maxV = prices[size-1];
        f2[size-1] = 0;
        for (int i = size-2; i >= 0; i--){
            maxV = std::max(maxV, prices[i]);
            f2[i] = std::max(f2[i+1], maxV - prices[i]);
        }

        int sum = 0;
        for (int i = 0; i < size; i++)
            sum = std::max(sum, f1[i] + f2[i]);

        return sum;
    }
};


int main()
{
    vector<int>prices;
    prices.push_back(1);
    prices.push_back(2);
    Solution s;
    s.maxProfit(prices);
    return 0;
}

 

 

 

 

 

 

EOF


免責聲明!

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



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