LeetCode: Best Time to Buy and Sell Stock I、II、III




Title three:

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

說明:求兩個交易利潤的最大值,其中在第一次交易完成前不能進行第二次交易,也就是第二次購買的時間值小於或等於第一次賣出的時間值。

將prices拆分爲兩部分,分別利用題一中的方法進行求兩部分的最大利潤值然後求和。時間複雜度爲O(n^2)

或者先前向遍歷求出一個個值之前的最大利潤值,再後面遍歷一個個值之後最大利潤值,然後進行求和得到最大值。時間複雜度O(n)

pro1[i]:表示在0 --- i之前完成一次交易的最大利潤

pro2[j]:表示在j --- size-1之後完成一次交易的最大利潤值


程序:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int size=prices.size();
        if(0==size)
            return 0;
        vector<int> pro1(size);
        vector<int> pro2(size);
        int minval=prices[0];
        for(int i=1;i!=size;++i)
        {
            minval=std::min(minval,prices[i]);
            pro1[i]=std::max(pro1[i-1],prices[i]-minval);
        }
        int maxval=prices[size-1];
        for(int j=size-2;j>0;--j)
        {
            maxval=std::max(maxval,prices[j]);
            pro2[j]=std::max(pro2[j+1],maxval-prices[j]);
        }
        int sum=0;
        for(int i=0;i!=size;++i)
        {
            sum=std::max(sum,pro1[i]+pro2[i]);
        }
        return sum;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章