[LeetCode] 121. Best Time to Buy and Sell Stock

원숭2·2022년 2월 12일
0

LeetCode

목록 보기
43/51

문제

풀이

  1. 이득값, 최솟값 변수를 각각 선언해 줌.
  2. for문을 돌며, 최솟값을 갱신하면서 기존 이득값과 최댓값 - 최솟값의 차액을 계속 비교하며 큰 값을 저장해줌.

코드

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        min_price = max(prices)
        
        for p in prices :
            min_price = min(min_price, p)
            profit = max(max_price, p - min_price)
        
        return profit

0개의 댓글