[Leetcode 123, Hard] Best Time to Buy and Sell Stock III

Problem:

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Analysis:


Solutions:

C++:

    int maxProfit(vector<int> &prices) 
    {
        if(prices.size() <= 1)
            return 0;

        int max_left = 0;
        vector<int> maxs_from_left;
        maxs_from_left.push_back(0);
        int min_price = prices[0];
        for(int i = 1; i < prices.size(); ++i) {
	        if(min_price > min(prices[i - 1], min_price))
	            min_price = prices[i - 1];

	        if(max_left < prices[i] - min_price)
	            max_left = prices[i] - min_price;
	            
	        maxs_from_left.push_back(max_left);
        }

        int max_two_trans = maxs_from_left[maxs_from_left.size() - 1];

        int max_price = prices[prices.size() - 1];
        for(int i = prices.size() - 2; i >= 1; --i) {
	        if(max_price < max(max_price, prices[i])) 
	            max_price = prices[i];
	            
	        if(max_two_trans < maxs_from_left[i - 1] + max_price - prices[i])
	            max_two_trans = maxs_from_left[i - 1] + max_price - prices[i];
        }

        return max_two_trans;
    }
Java:


Python:

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