LeetCode | 121. Best Time to Buy and Sell Stock

송치헌·2021년 9월 5일
0

Algorithm | LeetCode

목록 보기
11/15

문제

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:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Constraints:

1<=1<= prices.length <=105<=10^5
0<=0 <= prices[i] <=104<= 10^4

Python 풀이

from math import inf as INF #파이썬에서 무한대를 표현하는 변수

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price  = INF
        '''
        min_price를 처음에 9999라고 설정했는데 처음 비교하는 숫자가
        10000일 수도 있기 때문에 min_price를 어떤 숫자와 비교해도 
        그 숫자가 저장될 수 있도록 INF를 사용하였다.
        물론 이 문제에서는 prices[i]의 최대값이 10000으로 
        제한되어 있어서 min_price를 10001로 설정해도 되고
        min_price = prices[0] 로 설정해도 되지만 
        그렇지 않은 문제에서는 inf는 꽤나 유용하게 쓰인다.
        '''
        max_profit = 0 #주식 가격은 양수이므로 0으로 초기화

        #여기서 부터 dp
        for price in prices:
            min_price  = min(min_price, price)
            max_profit = max(max_profit, price - min_price)
        return max_profit

문제 설명

리스트에 날짜 순서대로 그 날의 주식 가격이 적혀있다. 먼저 주식을 사야 팔 수가 있으므로 [7, 5, 3, 2, 3] 인 배열이 존재할 때 7이 가장 높고 2가 가장 낮으므로 그 차이인 5가 정답! 이라고 외치면 틀리다는 것이다. 위의 예시에서는 가격이 2일 때 사서 3일 때 파는 것이 그나마 이익을 낼 수 있다.

접근법

먼저 리스트를 처음부터 순차로 돌며 가장 낮은 값을 저장 하고 현재 주식 가격과 가장 낮은 값의 차를 가장 높았던 profit과 비교하며 가장 높은 이익을 반환한다.

문제 풀이

  • 리스트의 인덱스를 0번부터 리스트의 끝까지 돌게 되면 주식을 시작하는 첫 날부터 주식이 끝나는 마지막 날까지 순서대로 돌게 된다.
  • 첫 날부터 for loop을 돌며 가장 낮았던 가격을 따로 저장해 놓는다(min_price)
  • 그리고 현재 주식 가격(prices[i])에서 가장 낮았던 가격(min_price)을 뺀 값과 가장 높았던 주식 가격(max_profit)을 비교하여 더 큰 값을 다시 max_profit에 저장한다.
profile
https://oraange.tistory.com/ 여기에도 많이 놀러와 주세요

0개의 댓글