Description: Given an array of size ‘n’, print those elements which are greater than all the elements on it’s right.

 
 
Example:
Input:

3  13   5  6   3   2   1

Output:

1  2  3  6  13 

Algorithm:

-Intialize a variable ‘max_so_far’ as last element.

-Print last element.

-Start scanning the array from the right(2nd last element) using index ‘i’:

        ->If max_so_far<arr[i], print arr[i] and assign max_so_far=arr[i];

Implementation using C:

/*The following function prints all elements that are greater than elements to the right of it.

Here arr[] is the received array and n the number of elements in it*/

void greater(int arr[],int n)

{

int i,j;

int max_so_far=arr[n-1];/*'max_so_far' stores maximum element obtained so far scanning from the right*/

printf("%d\t",arr[n-1]);/*Print last element*/

for(i=n-2;i>=0;i--)/*Scan the array from 2nd last element*/

{

   if(max_so_far<arr[i])

   {

      printf("%d\t",arr[i]);

      max_so_far=arr[i];

   }                  

}

}

Time Complexity:

O(n)

Go to top