#K77112. Next Greater Element
Next Greater Element
Next Greater Element
Given an array of integers, your task is to replace each element with the next greater element on its right. If no such element exists, replace it with -1.
More formally, for an array \(A = [a_1,a_2,\dots,a_n]\), for each \(a_i\) you need to find the first element \(a_j\) (where \(j > i\)) such that \(a_j > a_i\). If such an element exists, set \(result[i] = a_j\); otherwise, set \(result[i] = -1\).
For example, given the array [4, 5, 2, 10, 8], the output should be [5, 10, 10, -1, -1].
inputFormat
The input is given via standard input in the following format:
- The first line contains a single integer \(n\), representing the number of elements in the array.
- The second line contains \(n\) space-separated integers indicating the elements of the array.
outputFormat
Output the modified array as a single line of \(n\) space-separated integers, where each element is replaced by the next greater element on its right, or -1 if no such element exists.
## sample5
4 5 2 10 8
5 10 10 -1 -1
</p>