#1298
Maximum Candies You Can Get from Boxes
HardArrayBreadth-First SearchGraph TheoryBreadth-First Search (BFS)Graph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using BFS allows us to efficiently explore all boxes without revisiting them unnecessarily. We can track opened boxes and keys dynamically, ensuring we maximize candy collection.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a queue with the initial boxes and a set for opened boxes.
- 2Step 2: While the queue is not empty, process each box: collect candies, add keys, and enqueue contained boxes.
- 3Step 3: After processing a box, check if any keys can open new boxes and enqueue them.
solution.py23 lines
1def maxCandies(status, candies, keys, containedBoxes, initialBoxes):
2 from collections import deque
3 queue = deque(initialBoxes)
4 total_candies = 0
5 keys_set = set()
6 opened_boxes = set(initialBoxes)
7
8 while queue:
9 box = queue.popleft()
10 if status[box]:
11 total_candies += candies[box]
12 for key in keys[box]:
13 keys_set.add(key)
14 for new_box in containedBoxes[box]:
15 if new_box not in opened_boxes:
16 opened_boxes.add(new_box)
17 queue.append(new_box)
18 for key in list(keys_set):
19 if key not in opened_boxes:
20 opened_boxes.add(key)
21 queue.append(key)
22 keys_set.remove(key)
23 return total_candiesℹ
Complexity note: This complexity arises because we process each box once and manage keys and opened boxes efficiently.
- 1Using BFS allows us to explore all reachable boxes efficiently.
- 2Tracking keys and opened boxes dynamically prevents unnecessary revisits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.