[Python] 주식 가격

hyeon·2021년 2월 8일
0

Programmers

목록 보기
2/18

1 Try

효율성 Failed

def solution(prices):
    answer = []
    for i, p in enumerate(prices[:-1]):
        answer.append(0)
        for j, d in enumerate(prices[i+1:]):
            answer[i] += 1
            if d < p:
                break
                
    answer.append(0)
    
    return answer

Passed

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

others

def solution(prices):
    n = len(prices)
    # 1. answer를 prices 길이와 맞춘다.
    answer = [0] * n
    # 2. 스택 생성
    st = []
    # 3. 0 ~ n-1 초까지 순회
    for i in range(n):
        # 1. 스택 비지 않고, prices[top] > prices[i] 이라면 다음 반복
        # 1-1. 스택에서 마지막에 저장된 시간 top 꺼냄
        # 1-2. answer[top]에 i - top을 저장
        while st and prices[st[-1]] > prices[i]:
            top = st.pop()
            answer[top] = i - top
        # 2. 스택에 현재 시간 i 저장
        st.append(i)
    
    # 4. 만약 스택이 남아있다면, 스택이 빌 때까지 다음 반복
    while st:
        # 1. 스택에서 마지막에 저장된 시간 top 꺼냄
        # 2. answer[top]에 가장 마지막 시간 n - i 에서 top을 뺸 시간 저장
        top = st.pop()
        answer[top] = n - 1 - top
    
    return answer
  • 괄호 문제가 생각났음.
profile
바스락바스락

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN