Leetcode #1298: Maximum Candies You Can Get from Boxes
In this guide, we solve Leetcode #1298 Maximum Candies You Can Get from Boxes in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Breadth-First Search, Graph, Array
Intuition
The data forms a graph, so we should explore nodes and edges systematically.
A traversal ensures we visit each node once while maintaining the needed state.
Approach
Build an adjacency list and traverse with BFS or DFS.
Aggregate results as you visit nodes.
Steps:
- Build the graph.
- Traverse with BFS/DFS.
- Accumulate the required output.
Example
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.
Python Solution
class Solution:
def maxCandies(
self,
status: List[int],
candies: List[int],
keys: List[List[int]],
containedBoxes: List[List[int]],
initialBoxes: List[int],
) -> int:
q = deque()
has, took = set(initialBoxes), set()
ans = 0
for box in initialBoxes:
if status[box]:
q.append(box)
took.add(box)
ans += candies[box]
while q:
box = q.popleft()
for k in keys[box]:
if not status[k]:
status[k] = 1
if k in has and k not in took:
q.append(k)
took.add(k)
ans += candies[k]
for b in containedBoxes[box]:
has.add(b)
if status[b] and b not in took:
q.append(b)
took.add(b)
ans += candies[b]
return ans
Complexity
The time complexity is , and the space complexity is , where is the total number of boxes. The space complexity is , where is the total number of boxes.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.