프로그래밍/프로그래밍책📚

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

개발자 덕구🐾 2022. 1. 30. 13:59
728x90

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

 

Best Time to Buy and Sell Stock - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

< 내가 만든 시간초과 풀이 >

 

 def maxProfit(self, prices: List[int]) -> int:
        ans = 0
        tmp =0
        for i in range(len(prices)) :
            ans = max(tmp,ans)
            for j in range(i,len(prices)) :
                if prices[i] < prices[j] :  
                    if tmp < (prices[j] -  prices[i]) : tmp = prices[j] -  prices[i]
                        
        return ans

문제를 보고 무턱대로 완탐으로 만들었다. 

결과는 시간초과ㅎㅎ

 

 

 

파이썬 알고리즘 인터뷰의 2번째 풀이 - 저점과 현재 값과의 차이 계산으로 코드를 만들어보았다.

 

def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        min_price = sys.maxsize
        for price in prices :
            min_price = min(price, min_price) 
            profit = max(price - min_price, profit)
        return profit

 

저점을 찾아 O(n) 동안 가격차이를 계산하여 가격차이가 가장 큰 값을 반환하도록 만들면

시간초과가 발생하지않는다.

 

 

 

반응형