[translate by ChatGPT] This problem felt similar to the first one, but I misunderstood the problem statement at the beginning. I also feel that the description of the problem wasn’t very clear. Even toward the end I still wasn’t completely sure what the problem was trying to say.
Even when I tried to solve it based on my interpretation, I still couldn’t come up with a solution.
Later I saw that the official solution uses a segment tree, and only then did I understand the intended approach. At first I didn’t quite understand it, but eventually I figured out what the data structure is doing.
A segment tree has the following complexities:
Build: O(N)
Update: O(log N)
Query: O(log N)
I also learned that the build process works like this:
the first level has N nodes, the second level N/2, and so on, so the total build complexity is O(N).
The space complexity is about 4N.
In a complete tree you might only need 2N, but since the tree can become very unbalanced depending on the structure, we usually allocate 4N space.
Code
class SGT {
public:
SGT(int n) {
_n = n;
_val.resize(4*_n);
}
void build(const vector<int>& baskets, int idx, int left, int right) {
if(left == right) {
// it is left node
_val[idx] = baskets[left];
return;
}
int mid = (left + right) / 2;
build(baskets, 2*idx+1, left, mid);
build(baskets, 2*idx+2, mid+1, right);
_val[idx] = max(_val[2*idx+1], _val[2*idx+2]);
}
// set the idx as 0, and update all the way to the parent
void update(int idx) {
_val[idx] = 0;
int parent = (idx-1) / 2;
while(parent != 0) {
_val[parent] = max(_val[2*parent+1], _val[2*parent+2]);
parent = (parent-1) / 2;
}
}
int find(const int& cap) {
int left = 0, right = _n-1;
int idx = 0;
int ans = -1;
while(true) {
if(left == right) {
// reach leaf
if(_val[idx] >= cap) {
update(idx);
return _val[idx];
}
return -1;
}
int mid = (left + right) / 2;
int leftVal = _val[2*idx+1];
if(leftVal < cap) {
// left are all smaller, need to find the right one
idx = 2*idx + 2;
left = mid + 1;
} else {
idx = 2*idx + 1;
right = mid;
}
}
}
int _n;
vector<int> _val;
};
class Solution {
public:
int numOfUnplacedFruits(vector<int>& fruits, vector<int>& baskets) {
int n = fruits.size();
int ans = 0;
SGT sgt(n);
sgt.build(baskets, 0, 0, n-1);
for(int i = 0 ; i < n ; ++i) {
int cap = fruits[i];
if(sgt.find(cap) == -1) ++ans;
}
return ans;
}
};