← All problems

1298. Maximum Candies You Can Get from Boxes

HardOpen on LeetCodeProblem statement

Problem Statement

1298. Maximum Candies You Can Get from Boxes

Hard


You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:

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.

 

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.

 

Constraints:

Java

Source file
class Solution {
    public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
        int n = status.length, candyCt = 0;
        boolean[] vis = new boolean[n];
        Queue<Integer> bfs = new LinkedList<>();
        Set<Integer> closed = new HashSet<>();
        for (int b : initialBoxes)
            bfs.add(b);
        while (!bfs.isEmpty()) {
            int size = bfs.size();
            while (size-- > 0) {
                int top = bfs.poll();
                if (status[top] == 0) {// locked
                    closed.add(top);
                    continue;
                }
                if (vis[top]) // looted already
                    continue;
                candyCt += candies[top];
                // System.out.println(top + "\t" + candies[top] + "\t" + closed);
                vis[top] = true; // looted
                for (int nbr : containedBoxes[top])
                    bfs.add(nbr); // add to inventory
                for (int k : keys[top]) {
                    if (closed.contains(k)) {
                        closed.remove(k); // take out box from archive
                        bfs.add(k); // add to inventory
                    }
                    status[k] = 1; // unlock box
                }
            }
        }
        return candyCt;
    }
}