码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 309. Best Time to Buy and Sell Stock with Cooldown

时间:2019-08-04 18:03:54      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:数组   rest   滚动数组   info   http   down   n+1   技术   hold   

题意

买股票,中间买卖完一次后必须休息一下,求最大收益

题解

建议观看视频 ->->->-> https://www.bilibili.com/video/av31578180

状态转移图
技术图片

buy[i] 代表当前持有股票的最大收益
sell[i] 代表当前卖出股票的最大收益
rest[i] 代表当前休息的最大收益

class Solution {
public:
    // buy[i] -> util day i hold the stock max profit
    // sell[i] -> util day i sell the stock i max profit
    // rest[i] -> util day i rest max profit
    int maxProfit(vector<int>& prices) {
        const int INF = 0x3f3f3f3f;
        int len = prices.size();
        int buy[len+1] = {0};
        int sell[len+1] = {0};
        int rest[len+1] = {0};
        buy[0] = -INF; rest[0] = 0; sell[0] = 0;
        for(int i=1; i<=len; i++) {
            buy[i] = max(buy[i-1], rest[i-1] - prices[i-1]);
            sell[i] = prices[i-1] + buy[i-1];
            rest[i] = max(rest[i-1], sell[i-1]);
        }
        return max(sell[len], rest[len]);
    }
};

滚动数组优化空间

class Solution {
public:
    // buy[i] -> util day i hold the stock max profit
    // sell[i] -> util day i sell the stock i max profit
    // rest[i] -> util day i rest max profit
    int maxProfit(vector<int>& prices) {
        const int INF = 0x3f3f3f3f;
        int len = prices.size();
        int buy[2] = {0};
        int sell[2] = {0};
        int rest[2] = {0};
        buy[0] = -INF; rest[0] = 0; sell[0] = 0;
        for(int i=1; i<=len; i++) {
            buy[i % 2] = max(buy[(i-1) % 2], rest[(i-1) % 2] - prices[i-1]);
            sell[i % 2] = prices[i-1] + buy[(i-1) % 2];
            rest[i % 2] = max(rest[(i-1) % 2], sell[(i-1) % 2]);
        }
        return max(sell[len%2], rest[len%2]);
    }
};

leetcode 309. Best Time to Buy and Sell Stock with Cooldown

标签:数组   rest   滚动数组   info   http   down   n+1   技术   hold   

原文地址:https://www.cnblogs.com/Draymonder/p/11298982.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!