1944. Number of Visible People in a Queue

Description

image-20210923225826173

image-20210923225846950

Solution

Using monotone stack, look into preceding first number larger than current one.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<int> res(n, 0);
stack<int> stk;
for(int i = n-1; i >= 0; i--){
while(!stk.empty() && stk.top() < heights[i]){
res[i]++;
stk.pop();
}
if(!stk.empty())
res[i]++;
stk.push(heights[i]);
}
return res;
}
};

image-20210923230226243