[파이썬 알고리즘 인터뷰] 주식을 사고팔기 가장 좋은 시점

2021. 1. 8. 13:28노트/Algorithm : 알고리즘

주식을 사고팔기 가장 좋은 시점

한번의 거래로 낼 수 있는 최대 이익을 산출하라.

  • 입력

[7,1,5,3,6,4]

  • 출력

5

  • 1일 때 사서 6일 때 팔면 5의 이익을 얻는다.
# 풀이 1. 브루트 포스로 계산 
def maxProfit(prices):
    max_price = 0 
    for i , price in enumerate(prices):
        for j in range(i,len(prices)):
            max_price = max(prices[j]-price, max_price)
            
    return max_price 
    
prices = [7,1,5,3,6,4]
maxProfit(prices)
>>> 5 
import sys
# 풀이 2. 저점과 현재 값과의 차이 계싼 
def maxProfit(prices):
    profit = 0 
    min_price = sys.maxsize
    
    # 최솟값과 최댓값을 계속 갱신 
    for price in prices:
        min_price = min(min_price,price)
        profit = max(profit, price - min_price)
        
    return profit
    
maxProfit(prices)
>>> 5