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 at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:
prevalue[i]=max(prices[i]-MIN,prevalue[i-1])
postvalue[i]=max(MAX-prices[i],postvalue[i-1])
求dp即可
class Solution(object):
def maxProfit(self,prices):
numbers=len(prices)
if not numbers:
return 0
MIN=prices[0]
prevalue=[0]
for i in range(1,numbers):
MIN=min(prices[i],MIN)
prevalue.append(max(prices[i]-MIN,prevalue[i-1]))
prices.reverse()
MAX=prices[0]
postvalue=[0]
for i in range(1,numbers):
MAX=max(prices[i],MAX)
postvalue.append(max(MAX-prices[i],postvalue[i-1]))
postvalue.reverse()
value=0
for i in range(numbers):
value=max(value,prevalue[i]+postvalue[i])
return value