[leetcode]Best Time to Buy and Sell Stock III

来源:互联网 发布:数据脱敏的常用方法 编辑:程序博客网 时间:2024/05/22 20:45
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (prices.empty()) return 0;
        int n = (int)prices.size();
        
        vector<int> max_profit_before(n);
        max_profit_before[0] = 0;
        int min_price = prices[0];
        for (int i = 1; i < n; i++) {
            min_price = min(prices[i], min_price);
            max_profit_before[i] = max(max_profit_before[i-1], prices[i] - min_price);
        }
        
        vector<int> max_profit_after(n);
        max_profit_after[n - 1] = 0;
        int max_price = prices[n - 1];
        for (int i = n - 2; i >= 0;  i--) {
            max_price = max(prices[i], max_price);
            max_profit_after[i] = max(max_profit_after[i+1], max_price - prices[i]);
        }
        
        int res = 0;
        for (int i = 0; i < n; i++) {
            res = max(res, max_profit_before[i] + max_profit_after[i]);
        }
        return res;
    }
};
原创粉丝点击