Leaders in an Array
Problem
A leader is a value that is strictly greater than every value to its right. The last value is always a leader. Print the leaders in their original order.
Constraints
- 1 <= n <= 10^5
Examples
Input
6 16 17 4 3 5 2
Output
17 5 2
Solutions
Checking every value against everything on its right costs O(n^2). One scan from the right with the running maximum costs O(n).
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The leaders.
* Approach: Scan from the right.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int[] solve(int[] a) {
// Step 1: Walk from the right end. Keep the biggest value seen so far on the right side.
int[] found = new int[a.length];
int count = 0;
long biggest = Long.MIN_VALUE;
for (int i = a.length - 1; i >= 0; i--) {
// Step 2: A value bigger than everything on its right is a leader.
if (a[i] > biggest) {
found[count++] = a[i];
biggest = a[i];
}
}
// Step 3: We found the leaders from right to left, so we reverse them.
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = found[count - 1 - i];
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(Arrays.stream(solve(a)).mapToObj(String::valueOf).collect(Collectors.joining(" ")));
}
}
Hints (1)
- Which direction do you scan?