LeetCode/Top Interview 150

121. Best Time to Buy and Sell Stock

hyunkookim 2024. 11. 26. 15:30

121. Best Time to Buy and Sell Stock

 

from typing import List

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # 초기 구매 가격을 첫 번째 날의 가격으로 설정
        buy_price = prices[0]  # 현재까지의 최저 구매 가격
        buy_idx = 0  # 구매가 이루어진 시점의 인덱스
        profit = 0  # 현재 판매에서 발생한 이익
        max_profit = 0  # 최대 이익 저장 변수

        # 두 번째 날부터 순회 시작 (첫 번째 날은 이미 구매 가격으로 설정됨)
        for i in range(1, len(prices)):
            # 현재 가격이 이전의 구매 가격보다 낮으면 새로운 구매 가격으로 갱신
            if prices[i] <= buy_price:
                buy_price = prices[i]  # 더 낮은 가격으로 구매
                buy_idx = i  # 구매 시점 갱신

            # 현재 가격이 구매 가격보다 크고, 판매가 구매 이후에 이루어질 경우
            if prices[i] > buy_price and i > buy_idx:
                profit = prices[i] - buy_price  # 이익 계산 (판매 가격 - 구매 가격)
                max_profit = max(max_profit, profit)  # 최대 이익 갱신

        # 최대 이익 반환
        return max_profit

'LeetCode > Top Interview 150' 카테고리의 다른 글

55. Jump Game  (0) 2024.11.26
122. Best Time to Buy and Sell Stock II  (0) 2024.11.26
189. Rotate Array  (0) 2024.11.26
169. Majority Element  (0) 2024.11.26
80. Remove Duplicates from Sorted Array II  (0) 2024.11.25