-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray_Leetcode_Leaders_StriverSheet.cpp
More file actions
49 lines (30 loc) · 1.51 KB
/
Array_Leetcode_Leaders_StriverSheet.cpp
File metadata and controls
49 lines (30 loc) · 1.51 KB
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
/*Leaders in an Array
Given an integer array nums, return a list of all the leaders in the array.
A leader in an array is an element whose value is strictly greater than all elements to its right in the given array. The rightmost element is always a leader. The elements in the leader array must appear in the order they appear in the nums array.
Examples:
Input: nums = [1, 2, 5, 3, 1, 2]
Output: [5, 3, 2]
Explanation: 2 is the rightmost element, 3 is the largest element in the index range [3, 5], 5 is the largest element in the index range [2, 5]
Input: nums = [-3, 4, 5, 1, -4, -5]
Output: [5, 1, -4, -5]
Explanation: -5 is the rightmost element, -4 is the largest element in the index range [4, 5], 1 is the largest element in the index range [3, 5] and 5 is the largest element in the range [2, 5]*/
class Solution {
public:
vector<int> leaders(vector<int>& nums) {
int n = nums.size();
int i=n-1;
int rightmax = INT_MIN;
vector<int> leader;
while(i>=0)
{
if(nums[i] > rightmax)
{
rightmax = nums[i]; //if ne hi check mar liya koun bada hai to max kyun dhundna hai direct assign kar do max
leader.push_back(nums[i]);
}
i--;
}
reverse(leader.begin(),leader.end()); //to preserve output order. or you can simply take an another vector push the output there then push from last index to the vector you are returning.
return leader;
}
};