Leetcode算法學習日誌-309 Best Time to Buy and Sell Stock with Cooldown

Leetcode 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]

題意分析

買賣股票,每次買必須在上一次賣完一天(或大於一天)以後,求最大收益是多少。

解法分析

這種買賣股票問題是典型的動態規劃問題,對於某一天的最大收益,分兩種情況,一種是這天hold了一支股票,另一種是手裏沒有股票。可以得到遞歸式如下:

hold[i]=max(hold[i-1],non[i-2]-price),non[i]=max(non[i-1],hold[i-1]+price)。對於第i天的收益和前一天的收益,可以用同一個變量表示,再前一天的可以用另一個新的變量表示,本題需要注意初始值得選取。C++代碼如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int preNon=0,non=0,hold=INT_MIN,temphold;
        for(auto price:prices){
            temphold=hold;//temphold is not necessary
            hold=max(hold,preNon-price);
            preNon=non;
            non=max(non,temphold+price);
        }
        return non;   
    }
};
preNon用來存儲non[i-2],由於hold的值要麼取hold,要麼爲preNon-price,當爲preNon-price時,non一定取前一次的non,所以不影響non的新值,因此temphold不必要。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章