Source of the topic:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
Test Instructions Analysis:
Similar to the above question, Array[i] represents the price of items for the first day, if only 2 times can be traded. Ask for maximum profit.
Topic Ideas:
This is a dynamic planning issue. It is not difficult to think of splitting the entire array into two parts. Then use two arrays First,second respectively array[:i] and array[i:] The maximum profit. Then the answer equals Max (First[i] + second[i + 1]).
Code (Python):
classsolution (object):defMaxprofit (Self, prices):""": Type Prices:list[int]: Rtype:int"""size=len (Prices)ifSize = = 0:return0 First,second= [0 forIinchRange (size)],[0 forIinchRange (size+1)] Minp=Prices[0] forIinchRange (size):ifPrices[i] <=MINP:MINP= Prices[i];first[i] = first[i-1] First[i]= Max (Prices[i]-minp,first[i-1]) Maxp= Prices[size-1] J= Size-1 whileJ >=0:ifPRICES[J] >=Maxp:maxp=Prices[j] Second[j]= Max (SECOND[J+1],MAXP-Prices[j]) J-= 1ans=0 forIinchRange (size): ans= Max (ans,first[i]+second[i+1]) returnAns
View Code
[Leetcode] (python): 123-best time to Buy and Sell Stock III