알고리즘
[algorithm] leetcode 121 - Best Time to Buy and Sell Stock (파이썬)
hyuuny
2022. 3. 14. 00:05
문제
배열 가격이 주어지는데, 여기서 가격은 당일 주식의 가격이다.
한 주식을 살 날을 선택하고 해당 주식을 팔 다른 날을 선택하여 이익을 극대화하려고 합니다.
이 거래로 얻을 수 있는 최대 이익을 반환
하고,
만약 당신이 어떠한 이익도 얻을 수 없다면, 0을 반환
하라.
leetcode 121 - Best Time to Buy and Sell Stock
코드
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
min_price = sys.maxsize
# 최솟값과 최댓값을 계속 갱신
for price in prices:
min_price = min(min_price, price)
profit = max(profit, price - min_price)
return profit