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

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

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();
        // 这个问题存在4个状态
        // 1. buy1:进行第一次购买
        // 2. sell1:进行第一次出手
        // 3. buy2:进行第二次购买
        // 4. sell2:进行第二次出手
        // 当进行完sell2时,即得出最好时机
        
        // 初始化,在第一天进行购买和出手后收益
        int buy1 = -prices[0];
        int sell1 = 0;
        int buy2 = -prices[0];
        int sell2 = 0;
        for(int i = 1; i < n; i++) {
            buy1 = max(buy1, -prices[i]);
            sell1 = max(sell1, buy1 + prices[i]);
            buy2 = max(buy2, sell1 - prices[i]);
            sell2 = max(sell2, buy2 + prices[i]);
        }
        return sell2;
    }
};
全部评论

相关推荐

喵_coding:年底缺人是短视频营造出来的 而且一般说的也很宽泛 不是特指后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务