Skip to main content
Back to problems
#1298
Hard Algorithms

Maximum candies you can get from boxes

Array Breadth-First Search Graph Theory
67.9% acceptance
Mar 1, 2026
772
225
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 ith box is open and 0 if the ith box is closed, candies[i] is the number of candies in the ith box, keys[i] is a list of the labels of the boxes you can open after opening the ith box. containedBoxes[i] is a list of the boxes you found inside the ith 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 and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return the maximum number of candies you can get following the rules above.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_candies(
    status: Vec<i32>,
    candies: Vec<i32>,
    keys: Vec<Vec<i32>>,
    contained_boxes: Vec<Vec<i32>>,
    initial_boxes: Vec<i32>,
  ) -> i32 {
    let n = status.len();
    let mut has_box = vec![false; n];
    let mut has_key = vec![false; n];
    let mut queued = vec![false; n];
    let mut total = 0;
    let mut queue = std::collections::VecDeque::new();

    for b in initial_boxes {
      let b = b as usize;
      has_box[b] = true;
      if status[b] == 1 && !queued[b] {
        queued[b] = true;
        queue.push_back(b);
      }
    }

    while let Some(b) = queue.pop_front() {
      total += candies[b];
      for &k in &keys[b] {
        let k = k as usize;
        has_key[k] = true;
        if has_box[k] && !queued[k] {
          queued[k] = true;
          queue.push_back(k);
        }
      }
      for &cb in &contained_boxes[b] {
        let cb = cb as usize;
        has_box[cb] = true;
        if (status[cb] == 1 || has_key[cb]) && !queued[cb] {
          queued[cb] = true;
          queue.push_back(cb);
        }
      }
    }
    total
  }
}