Post

[코테] 121. Best Time to Buy and Sell Stock

난이도:EasySolved

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float(inf)
        max_profit = 0

        for price in prices:
            min_price = min(min_price, price)
            curr_profit = price - min_price

            max_profit = max(max_profit, curr_profit)

        return max_profit

Other Solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        buy_price = prices[0]
        profit = 0

        for p in prices[1:]:
            if buy_price > p:
                buy_price = p
            
            profit = max(profit, p - buy_price)
        
        return profit
This post is licensed under CC BY 4.0 by the author.