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

Have you met this question in a real interview? 
Yes
Example

Given an example [4,4,6,1,1,4,2,5], return 6.

Note

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

這裏和之前的幾個不同之處在於,現在是最多隻能交易兩次。那也就是說,按理應該將其劃分爲兩段,[0, i], [i + 1, len -1], 分別求兩段能夠獲得的最大利潤,然後加起來就是兩次交易可以獲取的最大利潤。定義兩個數組A[i]表示前i個可以獲取的最大利潤,B[i]表示後i個可以獲取的最大利潤。對於數組A[i]就用Best Time to Buy and Sell Stock的方法求解,那麼對於數組B[i], 如何高效的求解?在求解A[i]的時候,是把第i個當做賣出的時間點, 那麼在求解B[i]的時候應該將i點看做在第i點購買的時候,產生的最大利潤,明白了這一點,那麼B[i] = [i + 1, len -1]中的最大值 - prices[i],這樣求出A[i],B[i]之後就只要再遍歷一遍,求出最大的利潤。

class Solution {
public:
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    //維護兩個數組,數組A[i]表示以前i個可以獲得的最大利潤,B[i]表示以後i個可以獲得的最大利潤
    int maxProfit(vector<int> &prices) {
        // write your code here
        int len = prices.size();
        if(len < 2)
            return 0;
        int *A = new int[len], *B = new int[len + 1];
        A[0] = 0;
        B[len - 1] = 0;
        B[len] = 0;
        int curMin = prices[0], tmpMax = 0;
        for(int i = 1; i < len; ++i)
        {
            A[i] = (prices[i] - curMin) >= tmpMax ? prices[i] - curMin : tmpMax;
            tmpMax = tmpMax < A[i] ? A[i] : tmpMax;
            curMin = curMin > prices[i] ? prices[i] : curMin;
        }
        
        int curMax = prices[len - 1];
        tmpMax = 0;
        for(int i = len - 2; i >= 0; --i)
        {
            B[i] = (curMax - prices[i]) >= tmpMax ? curMax - prices[i] : tmpMax;
            tmpMax = tmpMax < B[i] ? B[i] : tmpMax;
            curMax = curMax < prices[i] ? prices[i] : curMax;
        }
        
        int Max = 0;
        for(int i = 0; i < len; ++i)
        {
            Max = Max < A[i] + B[i + 1] ? A[i] + B[i + 1] : Max;
        }
        
        return Max;
    }
};


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