LeetCode - Best Time to Buy and Sell Stock II(122)

marafo·2021년 7월 17일
0

Easy - Greedy

Time Limit..

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        
        prices = [6, 1, 3, 2, 4, 7]
        descending = sorted(prices, reverse = True)
        ascending = sorted(prices)
        
        if len(prices) == 1 or prices == descending:
            return 0
        
        if prices == ascending:
            return prices[-1] - prices[0]
        
        answer = 0
        i = 0
        
        while i <= len(prices) - 2:
            gap = 0
            profit = 0
            if i <= len(prices) - 2 and prices[i] < prices[i + 1]:
                profit += prices[i + 1] - prices[i]
                for j in range(i + 2, len(prices)):
                    if prices[j] > prices[j - 1]: # 최대 수익 갱신
                        if j == len(prices) - 1:
                            profit = prices[j] - prices[i] 
                            answer += profit
                            break
                        else:
                            profit = prices[j] - prices[i] 
                                
                    elif prices[j] < prices[j - 1]: # 고점에서 꺾일 때
                        answer += profit
                        gap = j - i # 건너뛸 간격
                        i += gap
            else:
                i += 1
                        
        return answer
                        
                
profile
프론트 개발자 준비

0개의 댓글