-
Notifications
You must be signed in to change notification settings - Fork 0
/
Leaders in an array.cpp
62 lines (53 loc) · 1.19 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
//{ 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)
{
int mx = a[n - 1];
vector<int> ans;
ans.push_back(mx);
for (int i = n - 2; i >= 0; i--)
{
if (a[i] < mx)
continue;
mx = a[i];
ans.push_back(mx);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
//{ 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