LeetCode 122. Best Time to Buy and Sell Stock II

개발공부를해보자·2025년 3월 7일

LeetCode

목록 보기
78/95

파이썬 알고리즘 인터뷰 78번(리트코드 122번) Best Time to Buy and Sell Stock II
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

나의 풀이

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        stack = []

        for price in prices:
            if not stack or stack[-1] <= price:
                stack.append(price)
            else:
                profit += stack[-1] - stack[0]
                stack = [price]
        profit += stack[-1] - stack[0]
        
        return profit

다른 풀이

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        buy = prices[0]

        for sell in prices:
            if sell > buy:
                profit += sell - buy
            buy = sell

        return profit
  • 1 → 2→ 3 원으로 가격이 오를 때, 1에 사서 3에 판다고 생각해도 되지만,
  • 1에 사서 2에 팔고, 팔자마자 다시 2에 사서 3에 판다고 생각해도 되는구나.
profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글