-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAth largest element.txt
92 lines (62 loc) · 2.05 KB
/
Ath largest element.txt
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
Ath largest element
Problem Description
Given an integer array B of size N.
You need to find the Ath largest element in the subarray [1 to i] where i varies from 1 to N. In other words, find the Ath largest element in the sub-arrays [1 : 1], [1 : 2], [1 : 3], ...., [1 : N].
NOTE: If any subarray [1 : i] has less than A elements then output array should be -1 at the ith index.
Problem Constraints
1 <= N <= 100000
1 <= A <= N
1 <= B[i] <= INT_MAX
Input Format
First argument is an integer A.
Second argument is an integer array B of size N.
Output Format
Return an integer array C, where C[i] (1 <= i <= N) will have the Ath largest element in the subarray [1 : i].
Example Input
Input 1:
A = 4
B = [1 2 3 4 5 6]
Input 2:
A = 2
B = [15, 20, 99, 1]
Example Output
Output 1:
[-1, -1, -1, 1, 2, 3]
Output 2:
[-1, 15, 20, 20]
Example Explanation
Explanation 1:
for i <= 3 output should be -1.
for i = 4 , Subarray [1:4] has 4 elements 1, 2, 3 and 4. So, 4th maximum element is 1.
for i = 5 , Subarray [1:5] has 5 elements 1, 2, 3, 4 and 5. So, 4th maximum element is 2.
for i = 6 , Subarray [1:6] has 6 elements 1, 2, 3, 4, 5 and 6. So, 4th maximum element is 3.
So, output array is [-1, -1, -1, 1, 2, 3].
Explanation 2:
for i <= 1 output should be -1.
for i = 2 , Subarray [1:2] has 2 elements 15 and 20. So, 2th maximum element is 15.
for i = 3 , Subarray [1:3] has 3 elements 15, 20 and 99. So, 2th maximum element is 20.
for i = 4 , Subarray [1:4] has 4 elements 15, 20, 99 and 1. So, 2th maximum element is 20.
So, output array is [-1, 15, 20, 20].
struct comp{
bool operator()(int a,int b) {
return a>b;
}
};
vector<int> Solution::solve(int A, vector<int> &B) {
int n=B.size();
vector<int> ans(n);
priority_queue<int,vector<int> ,comp>pq;
for(int i=0;i<min(A,n);i++){
ans[i]=-1;
pq.push(B[i]);
}
ans[min(A-1,n-1)]=pq.top();
for(int i=A;i<n;i++){
if(pq.top()<B[i]){
pq.pop();
pq.push(B[i]);
}
ans[i]=pq.top();
}
return ans;
}