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.
6
16 17 4 3 5 2
17 5 2
class Solution {
public:
vector<int> leaders(int a[], int n){
vector<int> ans;
ans.push_back(a[n-1]);
int max_val = a[n-1];
for(int i = 1; i < n; ++i){
if(max_val <= a[n - i - 1]) {
ans.push_back(a[n - i - 1]);
max_val = a[n - i - 1];
}
}
reverse(ans.begin(), ans.end());
return ans;
}
};