Maximum Candies You Can Get from Boxes - Problem
You have n boxes labeled from 0 to n - 1. You are given four arrays:
status[i]is1if theithbox is open and0if closedcandies[i]is the number of candies in theithboxkeys[i]is a list of labels of boxes you can open after opening theithboxcontainedBoxes[i]is a list of boxes you find inside theithbox
You are given an integer array initialBoxes that contains the labels of boxes you initially have.
Rules:
- You can take all candies from any open box
- You can use keys found in opened boxes to open new boxes
- You can use boxes found inside opened boxes
Return the maximum number of candies you can get following the rules above.
Input & Output
Example 1 — Basic Case
$
Input:
status = [1,0,1,0], candies = [7,5,4,9], keys = [[],[],[1],[]], containedBoxes = [[],[],[],[]], initialBoxes = [0]
›
Output:
16
💡 Note:
Start with box 0 (open) → collect 7 candies. Box 2 is also open → collect 4 candies. Box 0 has no keys, box 2 gives key to box 1 → open box 1 and collect 5 candies. Total: 7+4+5=16
Example 2 — Keys Required
$
Input:
status = [1,0,0,0], candies = [1,1,1,1], keys = [[1,2],[3],[],[]], containedBoxes = [[],[],[],[]], initialBoxes = [0]
›
Output:
4
💡 Note:
Box 0 is open → collect 1 candy and get keys [1,2]. Open boxes 1,2 → collect 2 more candies and get key [3]. Open box 3 → collect 1 candy. Total: 1+1+1+1=4
Example 3 — Contained Boxes
$
Input:
status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[1,2],[],[]], initialBoxes = [0]
›
Output:
7
💡 Note:
Start with box 0 → collect 2 candies and find boxes [1,2]. Boxes 1,2 are both open → collect 3+2=5 candies. Total: 2+3+2=7
Constraints
- 1 ≤ status.length ≤ 1000
- status.length == candies.length == keys.length == containedBoxes.length == n
- 0 ≤ status[i] ≤ 1
- 1 ≤ candies[i] ≤ 1000
- 0 ≤ keys[i].length ≤ 1000
- 0 ≤ keys[i][j] < n
- 0 ≤ containedBoxes[i].length ≤ 1000
- 0 ≤ containedBoxes[i][j] < n
- All values in keys[i] are unique
- All values in containedBoxes[i] are unique
- 1 ≤ initialBoxes.length ≤ 1000
- 0 ≤ initialBoxes[i] < n
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Start with given boxes, some open, some closed, with keys and contained boxes
2
Iterative Opening
Open accessible boxes, collect candies, keys, and new boxes
3
Final Result
Sum of all candies from boxes that could be opened
Key Takeaway
🎯 Key Insight: Use BFS-style iteration to systematically open all reachable boxes - the order doesn't affect the total candy count
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code