수열의 크기가 1,000,000이다. O(NlogN)의 시간복잡도를 가진 알고리즘을 설계하면 풀 수 있을 것 같다. 그런데 이 문제는 O(N)의 시간복잡도로 풀 수 있다.
import sys
input = sys.stdin.readline
N = int(input())
st = list(map(int, input().split()))
targets = []
ans = [-1] * N
st.reverse()
idx = 0
targets.append((idx, st.pop()))
while st:
t = st.pop()
idx += 1
while targets and targets[-1][1] < t:
a, b = targets.pop()
ans[a] = t
targets.append((idx, t))
for i in ans:
print(i, end=' ')
문제풀기보다 그림그려서 설명하는게 어려움