[백준/BOJ][Python] 11501번 주식

Eunding·2024년 11월 26일
0

algorithm

목록 보기
57/107

11501번 주식

https://www.acmicpc.net/problem/11501


아이디어

예전에 풀었던 문제인데 그때는 문제를 보고도 이해가 안됐는데 지금은 이해가 잘된다. 확실히 성장하긴 했나보다.

처음에는 입력 리스트가 오름차순 정렬되어있을때, 내림차순 정렬되어있을 때 따로 생각했다.

def sol():
    temp_stock = stock[:]
    temp_stock.sort(reverse=True)
    # 내림차순이면 0
    if stock == temp_stock:
        return 0
    temp_stock.sort()
    # 오름차순이면 최댓값
    if stock == temp_stock:
        temp = sum(stock[:-1])
        return stock[-1]*(len(stock)-1) - temp

그리고 뒤죽박죽 주어질 때만 해결하면 된다고 생각했다.
ex) 1 1 3 1 2

	temp_max = 0
    answer = 0
    for i in range(len(stock)-1, -1, -1):
        if temp_max <= stock[i]:
            temp_max = stock[i]
        else: # temp_max > stock[i]
            answer += temp_max - stock[i]
    return answer

그래서 짠 코드는 리스트를 거꾸로 탐색하면서 그때까지 나온 최댓값을 저장하는 temp_max를 만들어 주식을 그때 팔았다고 생각했다.

물론 이렇게 해도 맞았지만 굳이 오름차순, 내림차순 구분하지 않아도 저 코드가 다 포함한다는 걸 깨달았고 최종적인 sol 함수는 다음과 같다.

def sol():
    temp_max = 0
    answer = 0
    for i in range(len(stock)-1, -1, -1):
        if temp_max <= stock[i]:
            temp_max = stock[i]
        else: # temp_max > stock[i]
            answer += temp_max - stock[i]
    return answer

확실히 오름차순, 내림차순 구분 안해주니 코드가 간결해졌다.


코드

import sys
input =  sys.stdin.readline

def sol():
    temp_max = 0
    answer = 0
    for i in range(len(stock)-1, -1, -1):
        if temp_max <= stock[i]:
            temp_max = stock[i]
        else: # temp_max > stock[i]
            answer += temp_max - stock[i]
    return answer

T = int(input())
for _ in range(T):
    day = int(input())
    stock = list(map(int, input().split()))
    print(sol())

0개의 댓글