leaders in array
L = last element
print L
for i = n-2 to 0
if array[i] > L
L = array[i]
print L
Suppose we have to check if 8 is greater than {0,3,5}. Normally we will check if 8
is greater than 0/3/5 individually. We can also do it quickly. All we need to do is
just find the maximum of {0,3,5} i.e. 5 and compare only 5 with 8.
We just need to check if an element of an array is greater than the maximum element
among all the elements to its right.
We will make a variable. Let's name it leader (L) and assign it the last element of
the array as it is a leader by default.
class Ideone {
// function for finding leaders
public static void leaderprint(int arr[], int n) {
// last element of an array is leader by default
int L = arr[n - 1];
System.out.println(L + " is a leader");
// for finding leaders in other elements of the array
for (int i = n - 2; i >= 0; i--)
{
if (arr[i] > L)
{
L = arr[i];
System.out.println(L + " is a leader");
}
}
}
public static void main(String[] args)
{
int[] arr = { 7, 6, 4, 5, 0, 1 };
int n = arr.length;
leaderprint(arr, n);
}
}