Say you had an array for which the ith element was the price of a given stock on day I Design a algorithm to find the MA Ximum profit. You are in most of the transactions. Note:you engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). This problem can be solved by two methods, the first solution is to scan from left to right and then scan from right to left to the largest maxpro in the array stack1 stack2 the last solution will stack1[i]+stack2[i+1] The maximum value that is obtained is the maximum value. The code is as follows
Class solution: # @param prices, a list of integer # @return An integer def maxprofit (self, prices): if Le N (Prices) ==0: return 0 stack1=[] stack2=[] lowprice=prices[0] maxpro=0 highprice=prices [-1] For index in range (LEN (prices)): lowprice=min (Lowprice,prices[index]) Maxpro=max (maxpro,prices[index]- Lowprice) stack1.append (Maxpro) maxpro=0 for index in reversed (range (len (prices))): Highprice =max (Highprice,prices[index]) Maxpro=max (Maxpro,highprice-prices[index]) Stack2.insert (0,maxpro) For index in range (LEN (prices)-1): Maxpro=max (maxpro,stack1[index]+stack2[index+1]) return Maxpro
The second approach is to use a dynamic programming approach to solve
I means the J-th means that J-transactions can be made altogether.
The globally optimal expression is G[j]=max (G[j],l[j])
The local optimal expression is the maximum expression of the current optimal and the previous global optimality plus the money that can be earned.
L[j]=max (G[j-1]+max (dif,0), l[j]+dif)
The specific code is as follows:
Class solution: # @param prices, a list of integer # @return An integer def maxprofit (self, prices): g=[0, 0,0] l=[0,0,0] for i in range (len (prices)-1): Dif=prices[i+1]-prices[i] for J in reversed (range (1,3) ): L[j]=max (G[j-1]+max (dif,0), l[j]+dif) G[j]=max (L[j],g[j]) return g[2]
best time to Buy and Sell Stock III leetcode Python