-
Notifications
You must be signed in to change notification settings - Fork 126
/
Leaders_in_an_array.cpp
76 lines (62 loc) · 1.68 KB
/
Leaders_in_an_array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//gfg problem
// Leaders in an array
/*
Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader.
Example :
Input:
n = 6
A[] = {16,17,4,3,5,2}
Output: 17 5 2
Explanation: The first leader is 17
as it is greater than all the elements
to its right. Similarly, the next
leader is 5. The right most element
is always a leader so it is also
included.*/
// { Driver Code Starts
// C++ program to remove recurring digits from
// a given number
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
//Function to find the leaders in the array.
public:
vector<int> leaders(int a[], int n){
vector<int> l;
unsigned int max = a[n-1];
for( int i =n-1; i >= 0; i--){
if(a[i] >= max){
max = a[i];
l.push_back(max);
}
}
reverse(l.begin(), l.end());
return l;
}
};
// { Driver Code Starts.
int main()
{
long long t;
cin >> t;//testcases
while (t--)
{
long long n;
cin >> n;//total size of array
int a[n];
//inserting elements in the array
for(long long i =0;i<n;i++){
cin >> a[i];
}
Solution obj;
//calling leaders() function
vector<int> v = obj.leaders(a, n);
//printing elements of the vector
for(auto it = v.begin();it!=v.end();it++){
cout << *it << " ";
}
cout << endl;
}
}
// } Driver Code Ends