처음에 O(n^2)의 시간복잡도로 풀었다가 시간 초과가 나서 어떻게 하면 시간복잡도를 줄일 수 있을까 고민해보았다.
설명이 더 어려우니 코드를 읽어보길 바란다... 나 설명 진짜 못하네
import sys
input = sys.stdin.readline
N = int(input())
tower = list(map(int, input().split()))
stack = []
res = [0] * N
for idx, val in enumerate(tower):
if idx == 0:
stack.append([idx, val])
continue
else:
while stack:
if val < stack[-1][1]:
res[idx] = stack[-1][0] + 1
break
else:
stack.pop()
stack.append([idx, val])
print(" ".join(map(str, res)))