LeetCode 121. Best Time to Buy and Sell Stock

개발공부를해보자·2025년 1월 9일

LeetCode

목록 보기
12/95

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

나의 풀이

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0
        
        profit = 0
        ground = prices[0]

        for price in prices:
            if price < ground:
                ground = price
            else:
                profit = max(profit, price - ground)
        
        return profit
        

그림을 그려보면 생각에 도움이 된다.

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글