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

来源:互联网 发布:端口的作用是什么 编辑:程序博客网 时间:2024/05/29 09:09

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:

0 0