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]
解法1:DP O(N) Time + O(N) Space
这题主要要想到用两个数组来记录每一天的两种状态。一个是第i天持有股票,一个是第i天未持有股票。
用sell和buy代表两个数组。buy就是第i天持有股票的投资组合的最大市值。sell就是第i天未持有股票时的投资组合的最大市值。
那么初始状态sell[0] = 0, buy[0] = -prices[0]这是表示如果第一天持有股票的话一定是买入操作,那么需要花去prices[0]的钱。
那么每一天投资组合的演化可以得出下面的关系
依此写出如下程序,如果要求的话可以对空间进一步优化成O(1)
C++
解法1: 另外一种解释
以下的说明直接来自leetcode discussion
|
|