[LeetCode] Maximum Candies You Can Get from Boxes

1298. Maximum Candies You Can Get from Boxes

You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:

  • status[i] is 1 if the ith box is open and 0 if the ith box is closed,
  • candies[i] is the number of candies in the ith box,
  • keys[i] is a list of the labels of the boxes you can open after opening the ith box.
  • containedBoxes[i] is a list of the boxes you found inside the ith box.

You are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.

Return the maximum number of candies you can get following the rules above.

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
class Solution {
public:
int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {
int res = 0;
unordered_set<int> close, key, vis;
queue<int> box;

for(auto& b : initialBoxes) {
if(status[b] == 1) box.push(b);
else close.insert(b);
}
for(int i = 0; i < status.size(); i++) {
if(status[i]) key.insert(i);
}
while(!box.empty()) {
int b = box.front(); box.pop();
if(vis.count(b)) continue;
vis.insert(b);
res += candies[b];
for(auto& k : keys[b]) {
if(close.count(k)) {
if(!vis.count(k))
box.push(k);
} else key.insert(k);
}
for(auto& c : containedBoxes[b]) {
if(key.count(c)) {
if(!vis.count(c))
box.push(c);
} else close.insert(c);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/23/PS/LeetCode/maximum-candies-you-can-get-from-boxes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.