Maximum Candies You Can Get from Boxes - Problem
Imagine you're exploring a mysterious treasure chamber filled with magical boxes containing candies! ๐ญ
You have n boxes labeled from 0 to n-1. Each box has unique properties:
- Status: Some boxes are initially open (status = 1), others are locked (status = 0)
- Candies: Each box contains a certain number of delicious candies
- Keys: Opening a box may reveal keys to unlock other boxes
- Hidden Boxes: Some boxes contain other boxes inside them!
You start with an array initialBoxes - the boxes you can access initially. Your mission is to collect the maximum number of candies possible by strategically opening boxes, using keys, and discovering hidden boxes.
Rules:
- You can only take candies from open boxes
- Keys found in opened boxes can unlock other boxes you possess
- Boxes found inside opened boxes are added to your collection
- You can only open boxes that you physically have AND have the right key/status for
Input & Output
example_1.py โ Basic Case
$
Input:
status = [1,0,1,0], candies = [7,5,4,9], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
โบ
Output:
16
๐ก Note:
Start with box 0 (open, 7 candies). Box 0 contains boxes 1,2. Open box 2 (open, 4 candies), get key to box 1. Open box 1 with key (5 candies). Box 1 contains box 3, but we can't open it (closed, no key). Total: 7+4+5=16
example_2.py โ All Boxes Accessible
$
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 with 1 candy and contains keys to boxes 1,2,3. We can open all boxes and collect all 4 candies.
example_3.py โ No Additional Boxes
$
Input:
status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = [0]
โบ
Output:
100
๐ก Note:
Only one box, already open. Simply collect its 100 candies.
Constraints
- 1 โค n โค 1000
- 0 โค status[i] โค 1
- 0 โค candies[i] โค 1000
- 0 โค keys[i].length โค n
- 0 โค keys[i][j] < n
- 0 โค containedBoxes[i].length โค n
- 0 โค containedBoxes[i][j] < n
- 1 โค initialBoxes.length โค n
- 0 โค initialBoxes[i] < n
- All values in initialBoxes are distinct
- All values in keys[i] are distinct
- All values in containedBoxes[i] are distinct
Visualization
Tap to expand
Understanding the Visualization
1
Inventory Check
Check what boxes you have and what keys you possess
2
Opening Spree
Open all boxes you can (either already open or you have the key)
3
Collect Resources
Gather candies, add new keys to keychain, add new boxes to inventory
4
Repeat or Finish
If new boxes can be opened, repeat; otherwise you're done
Key Takeaway
๐ฏ Key Insight: This is a graph traversal problem where boxes are nodes and keys/containment create edges. BFS with state tracking ensures optimal O(n) solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code