1. 程式人生 > >[LeetCode 309] Best Time to Buy and Sell Stock with Cooldown(動態規劃及進一步優化)

[LeetCode 309] Best Time to Buy and Sell Stock with Cooldown(動態規劃及進一步優化)

題目內容

309 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:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

題目來源

題目簡述

買賣股票以獲得最大利益,一天只能進行一次操作,不能同時進行多筆交易,賣出後一天不能再買。

題目分析

用buy[i],sell[i],rest[i]表示第i天進行相應操作後利潤最大值。顯然,可列出狀態轉移方程為
buy[i]=max(buy[i-1],rest[i-1]-prices[i])
sell[i]=max(sell[i-1],buy[i-1]+prices[i])
rest[i]=max(sell[i-1],cool[i-1],buy[i-1])
由第一式可推出buy[i]<rest[i]。由第二式可推出sell[i]>=rest[i]。所以第三式可化為rest[i]=sell[i-1]。顯然第一式中rest[i-1]=sell[i-2]。
簡化之後的狀態轉移方程為
buy[i]=max(buy[i-1],sell[i-2]-prices[i])
sell[i]=max(sell[i-1],buy[i-1]+prices[i])
即成為典型的動態規劃問題,程式碼與上題類似。
此時空間複雜度為O(n)。觀察上述方程並注意變數以適當地順序進行賦值,可以將空間複雜度降低到O(1)。具體程式碼如下。

程式碼示例

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len=prices.size();
        int buy=INT_MIN;
        int pre_buy=0;
        int pre_sell=0;
        int sell=0;
        for(int i=0;i!=len;i++)
        {
            pre_buy=buy;
            buy=max(pre_sell-prices[i],buy);
            pre_sell=sell;
            sell=max(pre_buy+prices[i],sell);

        }
        return
sell; } };