class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit1(self, prices):
# write your code here
maxprofit = 0
minprise = prices[0]
for i in range(1, len(prices)):
maxprofit = max(maxprofit, prices[i] - minprise)
minprise = min(minprise, prices[i])
return maxprofit
def maxProfit(self, prices):
# write your code here
maxprofit = 0
for i in range(1,len(prices)-2):
pricesLeft = prices[:i + 1]
pricesRight = prices[i + 1:]
maxprofit = max(maxprofit, self.maxProfit1('', pricesLeft) + self.maxProfit1('', pricesRight))
return maxprofit
————————————————————————————————————————————————————————————————分割线
a = Solution
prices = [1,3,5,2,4,6]
print(a.maxProfit(a, prices))
结果:
8
将prices数组分割为两个数组,分别求最大利润。再将最大利润求和,取最大值。其中有些问题,没有考虑一次买卖的结果。