您的位置:首页 > 其它

Best Time to Buy and Sell Stock III

2013-10-01 00:35 309 查看
很经典啊,先从前往后来一遍,再从后往前来一遍,最后得到结果。

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len=prices.size();
        if(len==0||len==1) return 0;
        vector<int> forward;
        vector<int> back;
        forward.assign(len,0);
        back.assign(len,0);
        
        int vally=prices[0];
        for(int i=0;i<len;i++){
            vally=min(vally,prices[i]);
            if(i>0){
                forward[i]=max(forward[i-1],prices[i]-vally);
            }
        }
        int res=0;
        int peak=prices[len-1];
        for(int i=len-1;i>=0;i--){
            peak=max(peak,prices[i]);
            if(i<len-1){
                back[i]=max(back[i+1],peak-prices[i]);
            }
            res=max(res,forward[i]+back[i]);
        }
        return res;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: