leetcode #122. best time to buy and sell stock II (updated)

wonderful world·2021년 11월 13일
0

leetcode

목록 보기
5/21

update: 2021/11/14 fixed the buy or sell condition for stock value. Previsouly, it was 0 but was ambiguous with buying stock with 0 value which is valid range.

recursive version

EMPTY=-1
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        def trade(stock, all_profit, prices):
            if prices==[]: 
                #print ('DONE', stock, all_profit)
                return all_profit
            #print(stock, all_profit, prices)
            profits = []
            current_price = prices[0]
            rest = prices[1:]
            # buy
            if stock == EMPTY:
                profits += [trade(current_price, all_profit, rest)]
                
            # sell
            if stock != EMPTY:
                profits += [trade(EMPTY, all_profit + current_price - stock, rest)]
                
            # do nothing
            profits += [trade(stock, all_profit, rest)]
            return max(profits)
            
        return trade(EMPTY, 0, prices)
        
profile
hello wirld

0개의 댓글