题解 | #买卖股票的最好时机(三)#

买卖股票的最好时机(三)

http://www.nowcoder.com/practice/4892d3ff304a4880b7a89ba01f48daf9

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 两次交易所能获得的最大收益
     * @param prices int整型vector 股票每一天的价格
     * @return int整型
     */
    int maxProfit(vector<int>& prices) {
        // write code here
        int n = prices.size();
        if (n <= 1)
            return 0;
        int buy1 = -prices[0], sell1 = 0;
        int buy2 = -prices[0], sell2 = 0;
        for (int i = 1; i < n; ++i)
        {
            buy1 = max(-prices[i], buy1);
            sell1 = max(prices[i] + buy1, sell1);
            buy2 = max(sell1 - prices[i], buy2);//当sell1大于0时,开始买第二支股票
            sell2 = max(prices[i] + buy2, sell2);
        }
        return sell2;
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务