Original title address: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
Test instructions
Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. You are in most of the transactions.
Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
The idea of solving problems: the "low buy and sell high" rule in the trading market (buy lower and sell)
Only two trades are allowed, and the problem is much harder than the first two. The solution is ingenious, a bit of dynamic planning means:
Open two arrays P1 and P2,p1[i] represent the maximum profit for an exchange before Price[i],
P2[i] represents the maximum profit for an exchange after Price[i].
The maximum value of p1[i]+p2[i] is the maximum value required,
The calculations of P1[i] and p2[i] need to be dynamically planned, and it is not difficult to understand the code.
classSolution:#@param prices, a list of integers #@return An integer defMaxprofit (Self, prices): N=len (Prices)ifN <= 1:return0 P1= [0] *n P2= [0] *N MINV=Prices[0] forIinchRange (1, N): Minv= Min (Minv, prices[i])#Find low and buy lowP1[i] = max (p1[i-1], prices[i]-MINV) MAXV= Prices[-1] forIinchRange (N-2,-1,-1): Maxv= Max (MAXV, Prices[i])#Find High and sell highP2[i] = max (p2[i + 1], MAXV-Prices[i]) Res=0 forIinchrange (N): Res= Max (res, p1[i] +P2[i])returnRes
[Leetcode] best time to Buy and Sell Stock III @ Python