11class  Solution :
22    def  maxProfit (self , prices ):
3-         min_price , max_profit  =  9223372036854775807 , 0 
4-         profits_before  =  [0  for  i  in  range (len (prices ))]
5-         for  i  in  range (len (prices )):
6-             min_price  =  min (prices [i ], min_price )
7-             max_profit  =  max (prices [i ] -  min_price , max_profit )
8-             profits_before [i ] =  max_profit 
9-         max_price , max_profit  =  - 9223372036854775808 , 0 
10-         profits_after  =  [0  for  i  in  range (len (prices ))]
3+         min_price , max_profit , max_profits  =  9223372036854775807 , 0 , []
4+         for  price  in  prices :
5+             min_price  =  min (min_price , price )
6+             max_profit  =  max (max_profit , price  -  min_price )
7+             max_profits .append (max_profit )
8+         max_price , max_profit_after , max_combined_profit  =  0 , 0 , 0 
119        for  i  in  reversed (range (len (prices ))):
12-             max_price  =  max (prices [i ],  max_price )
13-             max_profit  =  max (max_price  -  prices [i ],  max_profit )
14-             profits_after [ i ]  =  max_profit 
15-         return  reduce ( lambda   acc ,  i :  max ( profits_before [ i ]  +   profits_after [ i ],  acc ),  range ( len ( prices )),  0 ) 
10+             max_price  =  max (max_price ,  prices [i ])
11+             max_profit_after  =  max (max_profit_after ,  max_price  -  prices [i ])
12+             max_combined_profit  =  max ( max_combined_profit ,  max_profit_after   +   max_profits [ i ]) 
13+         return  max_combined_profit 
0 commit comments