This is the first solution to find the leader numbers in an array from the backward direction. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader
public class LeaderNumbersInArrayFromBackside {
public static void main(String args[]) {
int[] arrNums = { 10, 2, 41, 13, 8, 36, 7, 15, 21 };
int leadNum = arrNums[arrNums.length - 1];
// Processing the numbers in the backward direction
System.out.println("All the leader Numbers");
System.out.print(leadNum + " ");
/*
* For each number from the backside of the array checking whether it's left
* side number is large
*/
for (int k = arrNums.length - 1; k >= 0; k--) {
if (arrNums[k] > leadNum) {
leadNum = arrNums[k];
System.out.print(leadNum + " ");
}
}
}
}
OUTPUT:
All the leader Numbers
21 36 41

Leave a comment