[每日一题] (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)
解题思路
本题使用动态规划,解题思路类似于抢劫问题。使用3个变量free, cool, have来存储当前位置的最优解。
free用来存储到当前位置,状态为空闲时的最优解
have用来存储到当前位置,状态为持有股票时的最优解
cool用来存储到当前位置,状态为正在冷却时的最优解
状态转移矩阵为:
free = max(free, cool) # 当前free的最优解由上一时间free的最优解和cool的最优解得出
have = max(have, free-p) # 当前have的最优解由上一时间持有股票时的最优解和上一时间空闲而这一时间购买股票的最优解得出
cool = have + p #当前cool的最优解由上一时间持有股票的最优解再在这一时间卖出得出
Python: