problem

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

solution1

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""

def helper(prices, start, dp):
if len(prices) < 2:
return 0
ans = 0
for i in range(start, len(prices)):
for j in range(i + 1, len(prices)):
if dp[j+2] != -1:
ans = max(ans, prices[j] - prices[i] + dp[j+2])
else:
ans = max(ans, prices[j] - prices[i] + helper(prices, j+2, dp))
dp[start] = ans

return ans

dp = [-1] * (len(prices)+2)
return helper(prices, 0, dp)

solution2

sell[i] = max(buy[i-1] + price, sell[i-1])

总结

• 本文已收录于以下专栏：

【LEETCODE】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 ...

Leetcode: 309. Best Time to Buy and Sell Stock with Cooldown 有冷却机制的最优炒股问题

Leetcode: 309. Best Time to Buy and Sell Stock with Cooldown 有冷却机制的炒股问题-作者: Eswai (eswai@foxmail.com...
• eswai
• 2017-01-12 19:25
• 95

LeetCode解题报告 309. Best Time to Buy and Sell Stock with Cooldown[medium]

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)