-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay32.java
More file actions
46 lines (38 loc) · 1.53 KB
/
Copy pathDay32.java
File metadata and controls
46 lines (38 loc) · 1.53 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
/*Array Leaders
You are given an array arr of positive integers. Your task is to find all the leaders in the array. An element is considered a leader if it is greater than or equal to all elements to its right. The rightmost element is always a leader.
Examples:
Input: arr = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 2]
Explanation: Note that there is nothing greater on the right side of 17, 5 and, 2.
Input: arr = [10, 4, 2, 4, 1]
Output: [10, 4, 4, 1]
Explanation: Note that both of the 4s are in output, as to be a leader an equal element is also allowed on the right. side
Input: arr = [5, 10, 20, 40]
Output: [40]
Explanation: When an array is sorted in increasing order, only the rightmost element is leader.
Input: arr = [30, 10, 10, 5]
Output: [30, 10, 10, 5]
Explanation: When an array is sorted in non-increasing order, all elements are leaders. */
/*import java.util.*;
class Solution {
static ArrayList<Integer> leaders(int arr[]) {
ArrayList<Integer> result = new ArrayList<>();
int n = arr.length;
int maxFromRight = arr[n - 1];
result.add(maxFromRight);
// Traverse from right to left
for (int i = n - 2; i >= 0; i--) {
if (arr[i] >= maxFromRight) {
maxFromRight = arr[i];
result.add(maxFromRight);
}
}
// Reverse to maintain left-to-right order
Collections.reverse(result);
return result;
}
}
*/
/*⏱ Time & Space Complexity
Time Complexity: O(n)
Space Complexity: O(n) (for output list) */