-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy path3479.Fruits Into Baskets 3.cpp
More file actions
58 lines (49 loc) · 1.32 KB
/
3479.Fruits Into Baskets 3.cpp
File metadata and controls
58 lines (49 loc) · 1.32 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
50
51
52
53
54
55
56
57
58
class SegmentTree {
int N;
vector<int> tree;
public:
SegmentTree(const vector<int>& baskets) {
int n = baskets.size();
N = 1;
while (N < n) N <<= 1;
tree.resize(N << 1, -1);
// Set basket capacities at leaves
for (int i = 0; i < n; ++i)
tree[N + i] = baskets[i];
// Build the tree
for (int i = N - 1; i >= 1; --i)
tree[i] = max(tree[2 * i], tree[2 * i + 1]);
}
// Try placing a fruit of quantity `val` in a valid basket
bool placeFruit(int val) {
int idx = 1;
if (tree[idx] < val)
return false;
while (idx < N) {
if (tree[2 * idx] >= val)
idx = 2 * idx;
else
idx = 2 * idx + 1;
}
// Place fruit (consume basket)
tree[idx] = -1;
// Update tree upwards
while (idx > 1) {
idx >>= 1;
tree[idx] = max(tree[2 * idx], tree[2 * idx + 1]);
}
return true;
}
};
class Solution {
public:
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
SegmentTree seg(baskets);
int unplaced = 0;
for (int fruit : fruits) {
if (!seg.placeFruit(fruit))
++unplaced;
}
return unplaced;
}
};