Skip to content

Commit 85d7a8a

Browse files
authored
Create maximum-candies-you-can-get-from-boxes.cpp
1 parent cffaa16 commit 85d7a8a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {
7+
int result = 0;
8+
queue<int> q;
9+
for (const auto& box : initialBoxes) {
10+
q.emplace(box);
11+
}
12+
while (!q.empty()) {
13+
bool changed = false;
14+
for (int i = q.size() - 1; i >= 0; --i) {
15+
const auto box = q.front(); q.pop();
16+
if (!status[box]) {
17+
q.emplace(box);
18+
continue;
19+
}
20+
changed = true;
21+
result += candies[box];
22+
for (const auto& contained_key : keys[box]) {
23+
status[contained_key] = 1;
24+
}
25+
for (const auto& contained_box : containedBoxes[box]) {
26+
q.emplace(contained_box);
27+
}
28+
}
29+
if (!changed) {
30+
break;
31+
}
32+
}
33+
return result;
34+
}
35+
};

0 commit comments

Comments
 (0)