fork download
  1.  
  2.  
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7. vector<int> printLeaders(int arr[], int n) {
  8.  
  9. vector<int> ans;
  10.  
  11. // Last element of an array is always a leader,
  12. // push into ans array.
  13. int max = arr[n - 1];
  14. ans.push_back(arr[n-1]);
  15.  
  16. // Start checking from the end whether a number is greater
  17. // than max no. from right, hence leader.
  18. for (int i = n - 2; i >= 0; i--)
  19. if (arr[i] > max) {
  20. ans.push_back(arr[i]);
  21. max = arr[i];
  22. }
  23.  
  24.  
  25. return ans;
  26. }
  27.  
  28. int main() {
  29.  
  30. // Array Initialization.
  31. int n = 6;
  32. int arr[n] = {10, 22, 12, 3, 0, 6};
  33.  
  34. vector<int> ans = printLeaders(arr,n);
  35.  
  36.  
  37. for(int i = ans.size()-1;i>=0;i--){
  38.  
  39. cout<<ans[i]<<" ";
  40. }
  41.  
  42. cout<<endl;
  43. return 0;
  44. }
  45.  
  46.  
Success #stdin #stdout 0.01s 5268KB
stdin
Standard input is empty
stdout
22 12 6