Question -
Given an sorted array, your task is to find the leader elements from array.
note - an element is said to be leader of the array if element is greater element to all the right side of the elements.
Example -
Input : arr[] = {1, 2, 5, 3, 9, 10, 6 }
Output : 10, 6
Approach -
We pick an element and check that it is greater than all of its right element or not. if it is greater than all of its right elements then it is leader element.
Implementation -
#include<iostream>
using namespace std;
void findleader(int arr[],int n)
{
for(int i=0;i<n;i++){
int k=0;
for(int j=i+1;j<n;j++){
if(arr[i]<=arr[j]){
k=1;
break;
}
}
if(k==0)
cout<<arr[i]<<" ";
}
}
int main(int argc, char *argv[])
{
int n;
cout<<"Enter n : ";
cin>>n;
int arr[n];
cout<<"Enter values : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
findleader(arr,n);
}
Time complexity -O(n*n)
Extra space - O(1)
Comments
Post a Comment