LeetCode學習篇十八——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]

難度:medium 通過率:39.2%

題目可畫出有限狀態圖
這裏寫圖片描述
圖中有三個狀態,箭頭的指向表明了狀態的轉移過程,所以可以列出狀態轉移方程,假設第i天,則有:
f0[i] = max(f0[i-1], f2[i-1]);
f1[i] = max(f0[i-1]-prices[i], f1[i-1]);
f2[i] = f1[i-1] + prices[i];
可得代碼如下,時間複雜度:O(n)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() <= 1 ) return 0;
        vector<int> f0(prices.size());
        vector<int> f1(prices.size());
        vector<int> f2(prices.size());
        f0[0] = 0;
        f1[0] = -prices[0];
        f2[0] = INT_MIN;
        for(int i = 1; i < prices.size(); i++) {
            f0[i] = max(f0[i-1], f2[i-1]);
            f1[i] = max(f0[i-1]-prices[i], f1[i-1]);
            f2[i] = f1[i-1] + prices[i];
        }
        return f0[prices.size() -1]>=f2[prices.size() -1] ? f0[prices.size() -1] : f2[prices.size() -1];
    }
};
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章