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

来源:互联网 发布:淘宝欧缇丽旗舰店真假 编辑:程序博客网 时间:2024/06/06 09:24
class Solution {public:    int maxProfit(vector<int>& prices) {        int size = prices.size();        if (size == 0 || size == 1)            return 0;        if (size == 2)                return prices[1] > prices[0] ? prices[1] - prices[0] : 0;                int has[size] = {0};        int no[size] = {0};                has[0] = -prices[0];        no[0] = 0;        has[1] = max(-prices[0], -prices[1]);        no[1] = max(has[0] + prices[1], no[0]);        for(int i = 2; i < size; i++){            has[i] = max(no[i - 2] - prices[i], has[i - 1]);            no[i] = max(has[i - 1] + prices[i], no[i - 1]);        }        return no[size - 1];    }};

 动态规划。两个状态数组,持股与不持股。

 has[i]代表一个持股与不持股的序列,并且这个序列以持股为结尾(在第i天时是持股的)

 no[i]代表一个持股与不持股的序列,并且此序列在第i天不持股

状态转移方程

has[i] = max(no[i - 2] - prices[i], has[i - 1]);no[i] = max(has[i - 1] + prices[i], no[i - 1]);
讲道理这题对于没参加acm的我来说,想出这个解释挺费劲的。

然而这种题对于ACM大佬并不算秀,只是基本操作。

再努力刷题吧。

阅读全文
0 0