Best Time to Buy and Sell Stock III 买卖股票的最好时间

来源:互联网 发布:设计淘宝店要多少钱 编辑:程序博客网 时间:2024/04/28 09:40
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n=prices.size();
        if(n<2)
        return 0;
        vector<int> left(n,0);
        vector<int> right(n,0);
        int minbuy=prices[0];
         left[0]=0;
        for(int i=1;i<n;i++)
        {
            left[i]=max(left[i-1],prices[i]-minbuy);
            minbuy=min(minbuy,prices[i]);
        }
        int maxsell=prices[n-1];
         right[n-1]=0;
        for(int i=n-2;i>=0;i--)
        {
            right[i]=max(right[i+1],maxsell-prices[i]);
            maxsell=max(maxsell,prices[i]);
        }
        int maxprofit=0;
        for(int i=0;i<n;i++)
        {
            maxprofit=max(maxprofit,left[i]+right[i]);
        }
        return maxprofit;
    }
};
0 0
原创粉丝点击