📒 Tech Note/알고리즘 & 자료구조

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

@Hadev 2022. 8. 20. 00:58

*알고리즘 스터디에 참여하면서 Blind 75 LeetCode Questions 목록에 있는 문제를 풀이합니다. 

문제: 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

풀이: 

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:
            return 0

        maxProfit = 0
        minPurchase = prices[0]
        for i in range(1, len(prices)):		
            maxProfit = max(maxProfit, prices[i] - minPurchase)
            minPurchase = min(minPurchase, prices[i])
        return maxProfit

주식의 최저값을 첫번째 인자를 넣어주고, 배열을 하나씩 조회하면서
(현재 가격 - 최저값)과 수익값 중, 최대값을 수익값으로 보고 바꿔준다. 
현재 가격과 수익값 중 최저값을 수익값으로 보고 바꿔준다.