You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Example 1
입력: prices = [7,1,5,3,6,4]
출력: 5
설명: 2일째에 주식을 사서 (가격 = 1) 5일째에 팝니다 (가격 = 6), 이익 = 6-1 = 5.
2일째에 사서 1일째에 판매하는 것은 허용되지 않습니다. 주식을 사기 전에 팔 수 없기 때문입니다.
Example 2
입력: prices = [7,6,4,3,1]
출력: 0
설명: 이 경우 거래가 이루어지지 않으므로 최대 이익 = 0입니다.
주식을 2일째 이후로 산 주식을 팔 때 최대 이익을 찾는 것이 목표입니다. 이를 위해 최저 구매 가격과 최대 판매 가격의 차이를 계산하여 최대 이익을 도출해야 합니다. 주의할 점은 주식을 사고 나서야 팔 수 있다는 것입니다.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
min_price = prices[0]
# 초기값을 prices[0]으로 하는 이유?
# ➡️ 최소 가격을 추척하기 초기 값을 설정
# ➡️ 알고리즘 시작 시점에서 오직 하나의 가격만 알고 있기 때문에 이걸로 초기값 가짐
for price in prices:
# price로 prices의 하나의 원소씩을 반복
# prices = [7,1,5,3,6,4]
# 첫 번째 반복으로 price 는 prices의 첫 번째 원소인 7
# 두 번쨰 반복으로 price는 prices의 두 번째 원소인 1
# 이런 식으로 마지막 원소까지 반복
profit = price - min_price
# 최대 이익을 알기 위해서 하나씩 최소 값과 뺴보면서 알아냄
# 최대 이익 갱신
max_profit = max(max_profit, profit)
# 반복할 때마다 여가서 위에 정한 최대값과 방금 계산한 최대값과 비교해서 최대값을 변경해줌
# 최소 구매 가격 갱신
min_price = min(min_price, price)
# 최대값 구하는 것과 같이 최소값을 비교해서 변경해주
return max_profit