Maximum Candies You Can Get from Boxes

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 i^th box is open and 0 if the i^th box is closed.
  • candies[i] is the number of candies in the i^th box.
  • keys[i] is a list of the labels of the boxes you can open after opening the i^th box.
  • containedBoxes[i] is a list of the boxes you found inside the i^th 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, use the keys in it to open new boxes, and use the boxes you find in it.

Return the maximum number of candies you can get following the rules above.

Example 1
Inputstatus = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]
Output16
Starting with box 0, you collect candies from boxes 0, 2, and then 1 after finding its key, but box 3 remains closed, for a total of 16 candies.
Example 2
Inputstatus = [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]
Output6
Opening box 0 gives you boxes 1 through 5 and their keys, so you can collect all 6 candies.

Constraints

  • n == status.length == candies.length == keys.length == containedBoxes.length
  • 1 <= n <= 1000
  • status[i] is either 0 or 1.
  • 1 <= candies[i] <= 1000
  • 0 <= keys[i].length <= n
  • 0 <= keys[i][j] < n
  • All values of keys[i] are unique.
  • 0 <= containedBoxes[i].length <= n
  • 0 <= containedBoxes[i][j] < n
  • All values of containedBoxes[i] are unique.
  • Each box is contained in one box at most.
  • 0 <= initialBoxes.length <= n
  • 0 <= initialBoxes[i] < n

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate