개발/Leetcode

Leetcode 121. Best Time to Buy and Sell Stock

지산동고라니 2023. 6. 24. 10:51

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

 

Best Time to Buy and Sell Stock - LeetCode

Can you solve this real interview question? Best Time to Buy and Sell Stock - 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 choosin

leetcode.com

 

문제

각 일자에 해당하는 가격의 정보가 담긴 배열 prices가 주어진다. 이 배열을 가지고 구매 일자 그리고 구매 일자 이후의 판매 일자를 통해 얻을 수 있는 최대의 이익을 반환하라

 

코드

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        minPrice = max(prices)

        for price in prices:
            if minPrice > price:
                minPrice = price
            elif minPrice < price:
                profit = max(profit,  price - minPrice)

        return profit

 

prices 배열을 순회하면서 최소 가격을 찾는다. 그와 동시에 최소가격을 가지고 최대의 이익을 얻을 수 있는 쌍을 찾아야 하는 문제이기에 최소가격과 현재 가격을 비교해 최대의 이익을 찾아 반환하는 코드