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.
Example 1:
Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0] Output: 16 Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2. In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed. Total number of candies collected = 7 + 4 + 5 = 16 candy.
Example 2:
Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0] Output: 6 Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6.
Constraints:
n == status.length == candies.length == keys.length == containedBoxes.length1 <= n <= 1000status[i] is either 0 or 1.1 <= candies[i] <= 10000 <= keys[i].length <= n0 <= keys[i][j] < nkeys[i] are unique.0 <= containedBoxes[i].length <= n0 <= containedBoxes[i][j] < ncontainedBoxes[i] are unique.0 <= initialBoxes.length <= n0 <= initialBoxes[i] < nProblem Overview: You start with a set of boxes. Some are open, some are locked. Open boxes may contain candies, keys to other boxes, and additional boxes. The task is to collect the maximum number of candies you can access by strategically using keys and opening boxes as they become available.
Approach 1: Breadth-First Search (BFS) Traversal (O(n + m) time, O(n) space)
Model the problem as a traversal over boxes where each box acts like a node in a graph. A box becomes processable when two conditions are satisfied: you possess the box and you have its key (or it is initially open). Use a queue to process boxes as soon as they become accessible. Track three states: boxes you currently have, keys you own, and boxes already opened. When you open a box, collect its candies, add any discovered boxes to your inventory, and store newly found keys. If a key unlocks a box you already have, immediately enqueue it for processing. Each box is processed at most once, so the traversal runs in O(n + m), where n is the number of boxes and m is the total number of keys and contained boxes discovered. Space complexity is O(n) for tracking visited boxes and queues. This approach naturally fits problems involving progressive discovery and is a classic use of Breadth-First Search over a dependency graph.
Approach 2: Depth-First Search (DFS) Exploration (O(n + m) time, O(n) space)
The same dependency structure can be explored using recursive or stack-based DFS. Start from the initial boxes and attempt to open them whenever the key is available. When a box is opened, recursively explore any contained boxes and update the key inventory. If a locked box appears before its key, store it and revisit once the key is discovered. The key insight is that traversal order does not change the final candy count as long as every newly unlocked box is eventually explored. DFS maintains the same complexity bounds: O(n + m) time for processing each box and edge-like relationship once, and O(n) auxiliary space for recursion or stacks. This version frames the problem as a graph reachability task similar to exploring nodes in a graph with conditional access.
Both methods rely on maintaining state about which boxes you possess and which keys unlock them. The problem becomes manageable once you treat boxes and keys as relationships in a traversal structure rather than simulating random opening attempts.
Recommended for interviews: The BFS approach is usually preferred because the queue directly represents boxes that just became accessible. It demonstrates clear reasoning about state transitions and mirrors typical solutions for unlocking dependencies in array-indexed structures. DFS works as well, but BFS tends to be easier to reason about and debug during interviews.
This approach uses a queue to process boxes in a breadth-first manner. You begin with the initial boxes, popping them one by one, collecting candies if they are open, and adding contained boxes and keys to respective sets. Keys allow you to open new boxes, which are then also added to the queue for further processing. This ensures all accessible boxes are eventually opened.
Keep track of opened boxes to avoid reprocessing.
This Python implementation uses a deque (double-ended queue) for efficient popping of elements from the front. By utilizing a set for visited boxes, we ensure that each box is processed only once, even if it is enqueued multiple times due to multiple paths reaching it.
Time Complexity: O(n), where n is the total number of boxes since each box is processed at most once.
Space Complexity: O(n), due to storage of keys, boxes, and visited sets.
This approach involves using a stack to simulate depth-first traversal. Starting with the initial boxes, we push each box onto a stack, popping off the top to explore its contents, collect candies from open boxes, and record newly found keys and contained boxes. Recursive exploration continues as stacks simulate depth-first processing. Each box is processed only when it can be opened, ensuring the solution remains efficient.
The C code uses a simple static array to mimic a stack enabling depth-first processing. The 'opened' Boolean array prevents processing a box multiple times. Efficiency is maintained through iterative use of the stack for DFS.
C
JavaScript
Time Complexity: O(n), as with BFS, each box is visited once.
Space Complexity: O(n), based on the stack and opened array storage.
The problem gives a set of boxes, each of which may have a state (open/closed), candies, keys, and other boxes inside. Our goal is to use the initially given boxes to open as many more boxes as possible and collect the candies inside. We can unlock new boxes by obtaining keys, and get more resources through boxes nested inside other boxes.
We use BFS to simulate the entire exploration process.
We use a queue q to represent the currently accessible and already opened boxes; two sets, has and took, are used to record all boxes we own and boxes we have already processed, to avoid duplicates.
Initially, add all initialBoxes to has. If an initial box is open, immediately add it to the queue q and accumulate its candies.
Then perform BFS, taking boxes out of q one by one:
keys[box] and add any boxes that can be unlocked to the queue;containedBoxes[box]. If a contained box is open and has not been processed, process it immediately;Each box is processed at most once, and candies are accumulated once. Finally, return the total number of candies ans.
The time complexity is O(n), and the space complexity is O(n), where n is the total number of boxes.
| Approach | Complexity |
|---|---|
| Breadth-First Search (BFS) Approach | Time Complexity: O(n), where n is the total number of boxes since each box is processed at most once. Space Complexity: O(n), due to storage of keys, boxes, and visited sets. |
| Depth-First Search (DFS) Approach | Time Complexity: O(n), as with BFS, each box is visited once. Space Complexity: O(n), based on the stack and opened array storage. |
| BFS + Hash Set | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Breadth-First Search (BFS) | O(n + m) | O(n) | Best general solution when boxes unlock other boxes progressively |
| Depth-First Search (DFS) | O(n + m) | O(n) | Useful when implementing recursive exploration of box dependencies |
Maximum Candies You Can Get from Boxes | 2 Ways | Simple Intuition | Leetcode 1298 |codestorywithMIK • codestorywithMIK • 8,454 views views
Watch 9 more video solutions →Practice Maximum Candies You Can Get from Boxes with our built-in code editor and test cases.
Practice on FleetCode