xinyu04

导航

[Oracle] LeetCode 123 Best Time to Buy and Sell Stock III 双向DP

You are given an array prices where prices[i] is the price of a given stock on the \(i\)-th day.

Find the maximum profit you can achieve. You may complete at most two transactions.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Solution

有两种情况,一种就是分为两段递增的序列,还有一种就是直接最后一次减去第一次就是最大值。

因此我们用 \(left[i]\) 来表示 \(i\) 之前的左边序列得到的最大收益, \(right[i+1]\) 表示\(i+1\) 右边序列得到的最大收益。转移很明显,我们只需要维护一个 \(\text{leftmin, rightmax}\) 即可

点击查看代码
class Solution {
private:
    vector<long> left, right;
    long ans =0;
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        left = vector<long>(n,INT_MIN);
        right = vector<long>(n,INT_MIN);
        long leftmin = prices[0];
        for(int i=1;i<n;i++){
            left[i] = max(left[i-1],(long)prices[i]-leftmin);
            leftmin = min(leftmin, (long)prices[i]);
        }
        long rightmax = prices[n-1];
        for(int i=n-2;i>=0;i--){
            right[i] = max(right[i+1], (long)rightmax-prices[i]);
            rightmax = max(rightmax, (long)prices[i]);
        }
        ans=max(ans, left[n-1]);
        for(int i=1;i<n-1;i++){
            ans=max(ans, (long)left[i]+(long)right[i+1]);
        }
        return ans;
    }
};

posted on 2022-09-28 14:40  Blackzxy  阅读(10)  评论(0编辑  收藏  举报