Thursday, 11 July 2019

find leaders in array simple approach

#include<stdio.h>
#include<limits.h>
//the concept is to traverse array from right and comparing each element with
//it's max of left subpart and store the leader elements in other array.
//complexity:O(n)
int main()
 {
int t;
scanf("%d",&t);
while(t--)
{
    int n,max=INT_MIN;
    scanf("%d",&n);
    int a[n],b[n],count=0;
    for(int i=0;i<n;i++)  scanf("%d",&a[i]);
    for(int i=n-1;i>=0;i--)
     {
                   if(a[i]>=max)
          {
            max=a[i];
            b[count]=a[i];
             count++;
             }
              }
    for(int i=count-1;i>=0;i--) printf("%d ",b[i]);
    printf("\n");
    
   }

return 0;
}

No comments:

Post a Comment