본문 바로가기
Leetcode

[LeetCode] Best Time to Buy and Sell Stocks python

by YGSEO 2021. 4. 1.
728x90

1132 ms

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        max_profit, min_price = 0, float("inf")
        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)
        return max_profit

min_price를 min으로 업데이트 시켜주면서 element순서대로 작은 값으로 update

max_price를 max로 업데이트 시켜주면서 price-min_price(현재 포함해서 그전까지 가장 작은 값, 만약 현재랑 같다면 0이 됨)

 

이런 문제는 다음에는 무조건 바로 해결해야됨.

 

출처: github.com/jiapengwen/LeetCode/blob/master/Python/best-time-to-buy-and-sell-stock.py


944ms

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

 

 

728x90

댓글