Problem 39
Leaders in an Array
Easy · 10 pts · Array
Problem
An element of an array is a leader if it is strictly greater than every element to its right. The last element is always a leader, since nothing lies to its right. Print all leaders in the order they appear in the array. Instead of comparing every element with everything after it, scan from right to left while tracking the largest value seen so far. An element is a leader exactly when it is greater than that maximum. Collect the leaders and reverse them at the end to restore array order.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the leaders, space-separated, in array order.
Constraints
1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000
Example input
6 16 17 4 3 5 2
Example output
17 5 2
Explanation
In 16 17 4 3 5 2: 2 is last, so it is a leader. 5 is greater than 2, so it is a leader. 3 and 4 are not greater than 5. 17 is greater than everything after it, and 16 is not (17 follows it). The leaders are 17 5 2.