알고리즘 스터디

[Leetcode/파이썬]121. Best Time to Buy and Sell Stock

난쟁이 개발자 2025. 3. 28. 04:27
반응형

Best Time to Buy and Sell Stock

Difficulty: Easy


You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

 

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

 

Constraints:

  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104

 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = 10**4
        res = 0
        for price in prices :
            min_price = min(min_price, price)
            res = max(res, price - min_price)
            
        return res

딱 한 번, 최대의 이윤을 구하는 문제이다.

리스트 안의 최소 값을 구하고, 이후의 높은 주식 가격에 판매를 하여 최대 이윤이 얼마인지 얻을 수 있다.

그러나, for 문 에 min, max를 쓰는것이 아니라 한 번만 쓰면 되는거 아닌가 라는 생각을 할 수도 있다. 그러나 주식의 시세 차익을 얻기 위해서는 내가 주식을 산 이후의 가격을 보아야 하기 때문에 다음과 같이 진행을 하였다. 만약 조금이라도 시간을 줄이고 싶다면

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = prices[0]
        res = 0
        for price in prices :
            if min_price > price :
                min_price = price

            else :
                res = max(res, price - min_price)
            
        return res

이런식으로 for 문이 덜 돌아갈 수 있도록 할 수도 있다. 

반응형