[LeetCode] Number of Flowers in Full Bloom

2251. Number of Flowers in Full Bloom

You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers.

Return an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.

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
#define all(a) begin(a), end(a)
using namespace std;
class Solution {
public:
vector<int> fullBloomFlowers(vector<vector<int>>& f, vector<int>& pp) {
vector<pair<int,int>> p;
int n = f.size(), m = pp.size();
for(int i = 0; i < m; i++) {
p.push_back({pp[i], i});
}
sort(all(p));
sort(all(f));
vector<int> res(m);
int i = 0, j = 0, sum = 0;
priority_queue<int, vector<int>, greater<int>> pq;
while(i < n and j < m) {
int lo = f[i][0];
while(!pq.empty() and pq.top() < lo) {
while(j < m and p[j].first <= pq.top()) {
res[p[j++].second] = sum;
}
pq.pop();
sum--;
}
while(j < m and p[j].first < lo) res[p[j++].second] = sum;

while(i < n and f[i][0] == lo) {
pq.push(f[i++][1]);
sum++;
}
}
while(!pq.empty() and j < m) {
while(j < m and p[j].first <= pq.top()) {
res[p[j++].second] = sum;
}
pq.pop();
sum--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/24/PS/LeetCode/number-of-flowers-in-full-bloom/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.