LeetCode/Top Interview 150

122. Best Time to Buy and Sell Stock II

hyunkookim 2024. 11. 26. 16:09

122. Best Time to Buy and Sell Stock II

 

https://youtu.be/3SJ3pUkPQMc?si=lGgpC5TAjAvrsyYM

 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(1, len(prices)):
            # 상승 구간에서만 매수-매도
            if prices[i] > prices[i - 1]:
                profit += prices[i] - prices[i - 1]
        return profit

 

그런데, prices[i] > prices[i-1] 보면, 하루 건너서만 이익 계산을 할수 있어. 어떻게 생각해?

 

 

결론

prices[i] > prices[i-1] 방식은 하루 건너 매매처럼 보이지만, 실제로는 모든 상승 구간을 적절히 처리하며, 최종 결과는 누적 상승과 동일합니다. 이 방식은 효율적이고, 문제 조건을 만족하는 적합한 접근법입니다.

'LeetCode > Top Interview 150' 카테고리의 다른 글

45. Jump Game II  (1) 2024.11.26
55. Jump Game  (0) 2024.11.26
121. Best Time to Buy and Sell Stock  (0) 2024.11.26
189. Rotate Array  (0) 2024.11.26
169. Majority Element  (0) 2024.11.26