美文网首页
309. Best Time to Buy and Sell S

309. Best Time to Buy and Sell S

作者: exialym | 来源:发表于2016-11-10 12:40 被阅读20次

    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());
    };
    

    相关文章

      网友评论

          本文标题:309. Best Time to Buy and Sell S

          本文链接:https://www.haomeiwen.com/subject/udxtpttx.html