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

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

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/

题目描述

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:

Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

C++ 实现 1

推荐文章: Most consistent ways of dealing with the series of stock problems.

通用的递推公式为:

T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i]) # sell
T[i][k][1] = max(T[i-1][k][1], T[i-1][k][0] - prices[i])  # buy

考虑到 cooldown, 本题的递推公式为:

T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i]) # sell
T[i][k][1] = max(T[i-1][k][1], T[i-2][k][0] - prices[i]) # buy

由于要 cooldown, 那么如果我们在第 i - 1 进行了股票的售出的话, 我们不能在第 i 天进行股票的购买. 因此上面公式中, 我们不能使用 T[i - 1][k][0] (表示在第 i 天手持 0 股票所获得的最大收益), 而应该使用 T[i - 2][k][0].

下面代码中使用 p_s0 表示 T[i - 1][k][0], 使用 pp_s0 表示 T[i - 2][k][0].

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int s0 = 0, s1 = INT32_MIN;
        int pp_s0 = 0;
        for (auto &p : prices) {
            int p_s0 = s0;
            s0 = std::max(s0, s1 + p);
            s1 = std::max(s1, pp_s0 - p);
            pp_s0 = p_s0;
        }
        return s0;
    }
};
发布了227 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/103882881