Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1298.html

1298. Maximum Candies You Can Get from Boxes (Hard)

Given n boxes, each box is given in the format [status, candies, keys, containedBoxes] where:

  • status[i]: an integer which is 1 if box[i] is open and 0 if box[i] is closed.
  • candies[i]: an integer representing the number of candies in box[i].
  • keys[i]: an array contains the indices of the boxes you can open with the key in box[i].
  • containedBoxes[i]: an array contains the indices of the boxes found in box[i].

You will start with some boxes given in initialBoxes array. 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 don't 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.

Example 3:

Input: status = [1,1,1], candies = [100,1,100], keys = [[],[0,2],[]], containedBoxes = [[],[],[]], initialBoxes = [1]
Output: 1

Example 4:

Input: status = [1], candies = [100], keys = [[]], containedBoxes = [[]], initialBoxes = []
Output: 0

Example 5:

Input: status = [1,1,1], candies = [2,3,2], keys = [[],[],[]], containedBoxes = [[],[],[]], initialBoxes = [2,1,0]
Output: 7

 

Constraints:

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

Related Topics:
Breadth-first Search

Solution 1.

  • class Solution {
        public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
            int maxCandies = 0;
            int length = status.length;
            Queue<Integer> queue = new LinkedList<Integer>();
            for (int initialBox : initialBoxes)
                queue.offer(initialBox);
            int index = 0;
            int size = queue.size();
            while (!queue.isEmpty()) {
                boolean flag = false;
                int box = queue.poll();
                if (status[box] == 0) {
                    queue.offer(box);
                    index++;
                    size = queue.size();
                } else {
                    maxCandies += candies[box];
                    int[] curKeys = keys[box];
                    int[] nextBoxes = containedBoxes[box];
                    if (curKeys != null && curKeys.length > 0) {
                        index = 0;
                        for (int key : curKeys)
                            status[key] = 1;
                    }
                    if (nextBoxes != null && nextBoxes.length > 0) {
                        index = 0;
                        for (int nextBox : nextBoxes)
                            queue.offer(nextBox);
                    }
                }
                if (index == size)
                    break;
            }
            return maxCandies;
        }
    }
    
    ############
    
    class Solution {
        public int maxCandies(
            int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
            int ans = 0;
            int n = status.length;
            boolean[] has = new boolean[n];
            boolean[] took = new boolean[n];
            Deque<Integer> q = new ArrayDeque<>();
            for (int i : initialBoxes) {
                has[i] = true;
                if (status[i] == 1) {
                    ans += candies[i];
                    took[i] = true;
                    q.offer(i);
                }
            }
            while (!q.isEmpty()) {
                int i = q.poll();
                for (int k : keys[i]) {
                    status[k] = 1;
                    if (has[k] && !took[k]) {
                        ans += candies[k];
                        took[k] = true;
                        q.offer(k);
                    }
                }
                for (int j : containedBoxes[i]) {
                    has[j] = true;
                    if (status[j] == 1 && !took[j]) {
                        ans += candies[j];
                        took[j] = true;
                        q.offer(j);
                    }
                }
            }
            return ans;
        }
    }
    
  • // OJ: https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/
    // Time: O(N)
    // Space: O(N)
    class Solution {
    public:
        int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {
            unordered_set<int> boxes, unusedKeys;
            queue<int> q;
            for (int n : initialBoxes) {
                if (status[n] == 1) q.push(n);
                else boxes.insert(n);
            }
            int ans = 0;
            while (q.size()) {
                int i = q.front();
                q.pop();
                ans += candies[i];
                for (int b : containedBoxes[i]) {
                    if (status[b] == 1) q.push(b);
                    else if (unusedKeys.count(b)) {
                        q.push(b);
                        unusedKeys.erase(b);
                    } else boxes.insert(b);
                }
                for (int k : keys[i]) {
                    if (boxes.count(k)) {
                        q.push(k);
                        boxes.erase(k);
                    } else unusedKeys.insert(k);
                }
            }
            return ans;
        }
    };
    
  • class Solution:
        def maxCandies(
            self,
            status: List[int],
            candies: List[int],
            keys: List[List[int]],
            containedBoxes: List[List[int]],
            initialBoxes: List[int],
        ) -> int:
            q = deque([i for i in initialBoxes if status[i] == 1])
            ans = sum(candies[i] for i in initialBoxes if status[i] == 1)
            has = set(initialBoxes)
            took = {i for i in initialBoxes if status[i] == 1}
    
            while q:
                i = q.popleft()
                for k in keys[i]:
                    status[k] = 1
                    if k in has and k not in took:
                        ans += candies[k]
                        took.add(k)
                        q.append(k)
                for j in containedBoxes[i]:
                    has.add(j)
                    if status[j] and j not in took:
                        ans += candies[j]
                        took.add(j)
                        q.append(j)
            return ans
    
    ############
    
    # 1298. Maximum Candies You Can Get from Boxes
    # https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/
    
    class Solution:
        def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:
            
            boxes = set(initialBoxes)
            bfs = [i for i in boxes if status[i]]
            
            for i in bfs:
                for b in containedBoxes[i]:
                    boxes.add(b)
                    if status[b]: bfs.append(b)
                
                for k in keys[i]:
                    if status[k] == 0 and k in boxes:
                        bfs.append(k)
                    
                    status[k] = 1
            
            return sum([candies[v] for v in bfs])
                        
    
  • func maxCandies(status []int, candies []int, keys [][]int, containedBoxes [][]int, initialBoxes []int) int {
    	ans := 0
    	n := len(status)
    	has := make([]bool, n)
    	took := make([]bool, n)
    	var q []int
    	for _, i := range initialBoxes {
    		has[i] = true
    		if status[i] == 1 {
    			ans += candies[i]
    			took[i] = true
    			q = append(q, i)
    		}
    	}
    	for len(q) > 0 {
    		i := q[0]
    		q = q[1:]
    		for _, k := range keys[i] {
    			status[k] = 1
    			if has[k] && !took[k] {
    				ans += candies[k]
    				took[k] = true
    				q = append(q, k)
    			}
    		}
    		for _, j := range containedBoxes[i] {
    			has[j] = true
    			if status[j] == 1 && !took[j] {
    				ans += candies[j]
    				took[j] = true
    				q = append(q, j)
    			}
    		}
    	}
    	return ans
    }
    

All Problems

All Solutions