Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:做seo需要什么技能 编辑:程序博客网 时间:2024/05/16 08:28

c++

class Solution {public:    int maxProfit(vector<int>& prices) {        if (prices.empty()) return 0;        int pre_buy = -prices[0];        int pre_sell = INT_MIN;        int pre_rest = 0;        for (int i = 1; i < prices.size(); ++i) {            int buy = max(pre_rest - prices[i], pre_buy);            int sell = max(pre_rest, pre_buy + prices[i]);            int rest = max(max(pre_rest, pre_buy), pre_sell);            pre_buy = buy;            pre_sell = sell;            pre_rest = rest;        }        return max(pre_sell, pre_rest);    }};

reference:
https://leetcode.com/discuss/71354/share-my-thinking-process
https://leetcode.com/discuss/72030/share-my-dp-solution-by-state-machine-thinking

0 0
原创粉丝点击