Code Kata | day 17 maxProfit

4844 단어 codekatacodekata

Q. prices는 배열이며, 각 요소는 매일의 주식 가격입니다. 만약 한 번만 거래할 수 있다면 = 사고 팔 수 있다면, 제일 큰 이익은 얼마일까요?


☑️ 0차

def maxProfit(prices):
  min_price = min(prices)
  start = prices.index(min_price)
  max_price = 0
  for i in range(start+1, len(prices)):
      max_price = max (prices[i], max_price)

  return max_price - min_price

Review

  • prices의 요소가 2개일 경우 for문이 실행되지 않음

☑️ 1차

def maxProfit2(prices):
   max_profit, min_price = 0, float('inf')
   for price in prices:
       min_price = min(min_price, price)
       profit = price - min_price
       max_profit = max(max_profit, profit)
   return max_profit

Review

  • inf : 가장 큰 수를 나타낸다. 최솟값을 저장하는 변수에 큰 값을 지정해야할 때 주로 사용한다.
  • prices의 매 요소마다 제일 작은 값, 수익(해당 요소 - 제일 작은 요소)를 계산해서 변수에 저장한다.

☑️ 2차

def maxProfit2(prices):
   max_profit, min_price = 0, float('inf')
   for price in prices:
       min_price = min(min_price, price)
       max_profit = max(max_profit, price - min_price)
   return max_profit

좋은 웹페이지 즐겨찾기