Skip to main content
Back to problems
Leetcode
Medium
Graphs
Queues
Sets
Hash Maps
Amazon
Google
Maximum Candies You Can Get From Boxes

Open boxes in a dependency chain to maximize the candies collected, using keys to unlock more boxes and nested boxes to continue the search.

Acceptance 100%
Problem Statement

You are given several boxes, some initially closed and some initially available to you. Each box may contain candies, keys to other boxes, and even more boxes.

You can open a box only if you currently have that box and either it is already open or you have the matching key for it. When you open a box, you collect all candies inside it and gain access to any keys and boxes it contains. Newly found boxes can later be opened if you obtain the right key.

Return the maximum total number of candies you can collect after repeatedly opening every box that becomes accessible.

Input Format

  • status: array indicating whether each box is initially open (1) or closed (0).
  • candies: array where candies[i] is the number of candies inside box i.
  • keys: list of lists where keys[i] contains the box indices whose keys are inside box i.
  • containedBoxes: list of lists where containedBoxes[i] contains the box indices found inside box i.
  • initialBoxes: array of box indices you initially have.

Output Format

  • Return an integer representing the maximum number of candies that can be collected.

Constraints

  • The number of boxes is small-to-medium and all indices are valid.
  • Each box can be opened at most once.
  • A box may contain zero or more candies, keys, and boxes.
  • If a box is closed and you do not have its key, you must wait until it becomes accessible later.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.