주식가격(python)

이민호·2021년 3월 12일
0

처음에는 deque를 안썼더니 시간오류가 났다;;
그래서 deque를 이용하여 조금 수정하니 다행히 시간통과가 되었다.

나의 풀이

<원리>
1. price[0]과 price[1:]을 비교한다.
2. price[0] <= price[1:] 이면 count += 1해주며, price[0] > price[1:]이면 count += 1 하고 break한다.
3. 반복문이 한번끝나면 answer =[] 에 count를 append 한다.

def solution(prices):
  from collections import deque
  prices = deque(prices)
  answer = []
  while prices:
      temp = prices.popleft()
      count = 0
      for k in prices:
          if temp <= k:
              count += 1
          else:
              count += 1
              break
      answer.append(count)
  return answer 
  1. deque를 사용하여 prices[0]을 popleft해준다.
  2. 가격이 떨어질때도 1초동안은 떨어지지 않는 것으로 간주하므로, else를 이용하여 count += 1한 후 break 한다.

다른사람의 풀이

answer = [0] * len(prices)를 해주어 count를 바로 넣어주는 방식이다.

def solution(prices):
  for i in range(len(prices)-1):
      for j in range(i, len(prices)-1):
          if prices[i] >prices[j]:
              break
          else:
              answer[i] +=1
  return answer

알게된 점

시간복잡도를 고민하였을때 반복문만을 중점으로 생각했었는데, 상수의 갯수나 입출력 부분에서도 영향을 받는다는 것을 알았다.

profile
life is fun

0개의 댓글

관련 채용 정보