Official
B - Nearest Taller Editorial by en_translator
You are asked to, for each \(i\), determine if there is a person taller than person \(i\) to the left of person \(i\), and if such person exists, who is the nearest to person \(i\) among them.
The answer to the problem can be found in the following way for example:
- Check if person \((i-1)\) is taller than person \(i\). If person \((i-1)\) is taller, the answer is \((i-1)\); terminate the algorithm.
- Check if person \((i-2)\) is taller than person \(i\). If person \((i-2)\) is taller, the answer is \((i-2)\); terminate the algorithm.
\(\vdots\)
- Check if person \(1\) is taller than person \(i\). If person \(1\) is taller, the answer is \(1\); terminate the algorithm.
- If nobody was found up to this step, there is no person taller than person \(i\) to the left of person \(i\), so the answer is \(-1\).
This problem can be solved by performing an iteration in reverse order using a for statement.
The problem can be solved by appropriately implementing the algorithm above. Be cautious in implementing a nested for loop.
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
ans = -1
for j in range(i - 1, -1, -1):
if a[j] > a[i]:
ans = j + 1
break
print(ans)
posted:
last update: