Saturday, June 19, 2021
Home coding Write a program to find leader in an array.

# Write a program to find leader in an array.

Given an integer array we have to find the leader of array and print the result on screen.

so what is leader of array?

if the particular element of array is greater than all element of its right side then that particular element is called leader of array.

Example:

``````Input:7,6,4,5,0,1
output:7 ,6, 5 ,1  is a leader``````

Logic:

``````step1 -start scanning from left to right
step2-keep maintaining the maximum element while scanning
step3-print the maximum element while iterating.``````

code:

```#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int maxr = a[n-1];
cout<<maxr<< " ";
for (int i=n-2; i >= 0; i--)
{
if (maxr <= a[i])
{
maxr = a[i];
cout << maxr << " ";
}
}
}
```

Output:

`````` input:
6
7 6 4 5 0 1
output:
1,5,6,7``````

Time Complexity:O(N)

Space Complexity:O(1)

- Advertisment -