← All coding problems
Leaders in an Array
easyPlacement Coding+10 XPTime limit 2s
An element is a leader if it is strictly greater than every element to its right. The last element is always a leader. In [16, 17, 4, 3, 5, 2] the leaders are 17 5 2.
Input:
- line 1:
n - line 2:
nintegers
Output: the leaders in the order they appear in the array, separated by spaces.
Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ values ≤ 10⁹.
Think about it: checking every element against everything on its right is O(n²). Walk from the right end instead and remember the largest value seen so far.
Sample input 1
6 16 17 4 3 5 2
Sample output 1
17 5 2
Sample input 2
4 1 2 3 4
Sample output 2
4
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).