This is the third solution to find the leader numbers in an array in the reverse direction using stream. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader
import java.util.stream.IntStream;
public class LeaderNumbersInArrayFromBacksideUsingStreams {
public static void main(String args[]) {
int[] arrNums = { 51, 2, 41, 13, 8, 36, 7, 15, 21 };
/*
* For each number from the reverse of the array checking whether it's left side
* number is large
*/
System.out.println("All the leader Numbers");
IntStream.range(0, arrNums.length).map(j -> arrNums.length - j - 1)
.filter(k -> arrNums[k] >= arrNums[arrNums.length - 1])
.forEach(x -> System.out.print(arrNums[x] + " "));
}
}
OUTPUT:
All the leader Numbers
21 36 41 51

Leave a comment