백준 11501번

DARTZ·2023년 4월 7일
0

알고리즘

목록 보기
109/135
import sys

stocks = []

for _ in range(N):
    M = int(sys.stdin.readline().rstrip())
    stocks.append(list(map(int, input().split())))

def solution(stocks):

    answer = []

    for stock in stocks:
        stock.reverse()
        maxValue = stock[0]
        benefit = 0
        for s in range(1, len(stock)):
            if stock[s] < maxValue:
                benefit += maxValue - stock[s]

            else:
                maxValue = stock[s]

        answer.append(benefit)

    return answer


for a in solution(stocks):
    print(a)

원래는 순서대로 진행하면서 다음 나오는 숫자가 현재 나오는 숫자보다 작으면 지금까지의 값들을 전부 계산하는 식으로 했다. 하지만 이럴경우
1 3 2 7 같은 경우 성립하지 않는다.

알고리즘을 풀 때, 다양한 방법으로 접근하는 연습이 필요해보인다. 거꾸로 생각해봤더니 쉽게 풀리는 문제였다.

profile
사람들이 비용을 지불하고 사용할 만큼 가치를 주는 서비스를 만들고 싶습니다.

0개의 댓글