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]
這道題看起來挺復(fù)雜的鸦列,其實(shí)也挺復(fù)雜蔬蕊。。烁设。
我沒想到好辦法甲棍,在discuss里找到了大神的辦法康铭。
總共有3個(gè)狀態(tài)毡鉴,初始狀態(tài)為S0井厌,狀態(tài)轉(zhuǎn)移關(guān)系如下:
于是可以得到遞推關(guān)系:
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
初始狀態(tài):
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的最后一個(gè)元素中找大的那個(gè),s1狀態(tài)不可能出現(xiàn)最大值址晕。
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());
};