Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2.
Method 2 (Scan from right)
Scan all the elements from right to left in array and keep track of maximum till now. When maximum changes it’s value, print it.
Read full article from Leaders in an array | GeeksforGeeks
Method 2 (Scan from right)
Scan all the elements from right to left in array and keep track of maximum till now. When maximum changes it’s value, print it.
void
printLeaders(
int
arr[],
int
size)
{
int
max_from_right = arr[size-1];
int
i;
/* Rightmost element is always leader */
printf
(
"%d "
, max_from_right);
for
(i = size-2; i >= 0; i--)
{
if
(max_from_right < arr[i])
{
printf
(
"%d "
, arr[i]);
max_from_right = arr[i];
}
}
}