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 = 3transactions = [buy, sell, cooldown, buy, sell]
这道题看起来挺复杂的,其实也挺复杂。。。
我没想到好办法,在discuss里找到了大神的办法。
总共有3个状态,初始状态为S0,状态转移关系如下:

状态转移图

于是可以得到递推关系:

s0[i] = Math.max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
s1[i] = Math.max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
s2[i] = s1[i - 1] + prices[i]; // Only one way from s1

初始状态:

s0[0] = 0; // At the start, you don't have any stock if you just rest
s1[0] = -prices[0]; // After buy, you should have -prices[0] profit. Be positive!
s2[0] = Number.MIN_VALUE; // Lower base case

最后在s0和s2的最后一个元素中找大的那个,s1状态不可能出现最大值。

var maxProfit = function(prices) {
    s0 = [0];
    s1 = [-prices[0]];
    s2 = [Number.MIN_VALUE];
    for (var i = 1;i < prices.length;i++) {
        s0[i] = Math.max(s0[i - 1], s2[i - 1]); // Stay at s0, or rest from s2
        s1[i] = Math.max(s1[i - 1], s0[i - 1] - prices[i]); // Stay at s1, or buy from s0
        s2[i] = s1[i - 1] + prices[i]; // Only one way from s1
    }
    return Math.max(s0.pop(),s2.pop());
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容