开发出来一个超时版本。从中吸取的教训就是不要轻易使用递归,节约时间成本的意识要加强。
Code:
class Solution(object):
def maxProfit_1(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit_1=0
min_price=float('inf')
for i in range(len(prices)):
min_price=min(min_price,prices[i])
max_profit_1=max(max_profit_1,prices[i]-min_price)
return max_profit_1
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
possible_profit=[]
for i in range(len(prices)-1):
for j in range(i+1,len(prices)):
if prices[j]>prices[i]:
a=self.maxProfit_1(prices[i:j+1])
b=self.maxProfit_1(prices[j+1:])
c=sum([a,b])
possible_profit.append(c)
if len(possible_profit)==0:
return 0
elif len(possible_profit)==1:
return possible_profit[0]
return max(possible_profit)
正确版本:
1.作者用到了动态规划(Dynamic Programming,DP)思想,思路异常清晰,就是选用了两个实时变化的量:一个代表当前时刻卖出股票可挣得的最大利润金额;一个代表当前时刻购买股票可挣得的最大利润金额。分别置于两个列表中,再叠加找出最大值即可。
2.另外,为了节约时间成本,作者坚持只用一个for 循环,一个实时变量从蛇头遍历,另一个从蛇尾开始遍历。
Code:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
sell,buy,n,minp,maxp=[0],[0],len(prices),prices[0],prices[-1]
for i in range(1,n):
minp=min(minp,prices[i])
maxp=max(maxp,prices[n-1-i])
sell.append(max(sell[-1],prices[i]-minp))
buy.append(max(buy[-1],maxp-prices[n-1-i]))
return max([sell[i]+buy[n-1-i]for i in range(n)])