알고리즘
[SWEA] 1859. 백만 장자 프로젝트 파이썬 풀이
besomilk
2021. 7. 21. 15:53
SW Expert Academy - D2 - 1859. 백만 장자 프로젝트

스택을 사용한 풀이
#1859 runtime error - 8/10
def test(a):
stack = []
maxnum = 0
for i in reversed(a):
if i>maxnum:
stack.append(i)
maxnum=i
else:
stack.append(0)
buy = 0
count = 0
sell = 0
for i in range(len(a)):
if stack.pop():
if buy != 0:
sell += a[i] * count - buy
buy = 0
count = 0
continue
buy += a[i]
count += 1
return sell
T = int(input())
for i in range(T):
N = int(input())
a = list(map(int, input().split()))
print('#{} {}'.format(i+1, test(a)))

런타임 에러 해결을 위해 반복문 하나로 끝내야겠다고 생각
T = int(input())
for test_case in range(1, T + 1):
N = int(input())
a = list(map(int, input().split()))
sell = 0
maxnum = a.pop()
for i in reversed(a):
if i>maxnum:
maxnum=i
else:
sell += maxnum - i
print('#{} {}'.format(test_case, sell))
