买卖股票的最佳时机 III
程序员文章站
2022-06-17 19:46:34
...
Python
class Solution:
def maxProfit(self, prices):
if prices==[]:return 0
length=len(prices)
b1= [0 for x in prices ]
s1 = prices[0]
b1[0]= 0
for i in range(1,length):
if s1 < prices[i]:
b1[i] = max(b1[i-1],prices[i]-s1)
else:
b1[i] = b1[i-1]
s1 = prices[i]
b2 = [0 for x in prices ]
s2 =prices[-1]
b2[-1]=0
for i in range(-2,-length,-1):
if s2 >prices [i]:
b2 [i] = max(b2[i+1],s2-prices[i])
else:
b2[i] = b2[i+1]
s2= prices[i]
result =0
for i in range(length):
result = max(result , b1[i]+b2[i])
return result