Skip to content

Latest commit

 

History

History
42 lines (33 loc) · 1.1 KB

leaders-in-an-array.md

File metadata and controls

42 lines (33 loc) · 1.1 KB

Leaders in an array

Problem Link

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.

Sample Input

6
16 17 4 3 5 2

Sample Output

17 5 2

Solution

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;
    }
};

Accepted

image