#1298
Maximum Candies You Can Get from Boxes
expert · 1060 · lc hard +32 · verified · 67.8% accepted · 772 likes · top 74%
Description
There are n boxes (labeled 0 to n - 1), described by four arrays:
- status[i]: 1 if box i is unlocked, 0 if locked.
- candies[i]: candies inside box i.
- keys[i]: which boxes you can unlock by opening box i.
- containedBoxes[i]: which boxes are found inside box i.
Starting with the boxes in initialBoxes, you may open any unlocked box you possess, collect its candies, gain its keys, and acquire the boxes inside it.
Return the maximum total candies collectable.
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.
Code
1
2
3