|
| 1 | +/** |
| 2 | + * 1298. Maximum Candies You Can Get from Boxes |
| 3 | + * https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and |
| 7 | + * containedBoxes where: |
| 8 | + * - status[i] is 1 if the ith box is open and 0 if the ith box is closed, |
| 9 | + * - candies[i] is the number of candies in the ith box, |
| 10 | + * - keys[i] is a list of the labels of the boxes you can open after opening the ith box. |
| 11 | + * - containedBoxes[i] is a list of the boxes you found inside the ith box. |
| 12 | + * |
| 13 | + * You are given an integer array initialBoxes that contains the labels of the boxes you initially |
| 14 | + * have. You can take all the candies in any open box and you can use the keys in it to open new |
| 15 | + * boxes and you also can use the boxes you find in it. |
| 16 | + * |
| 17 | + * Return the maximum number of candies you can get following the rules above. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} status |
| 22 | + * @param {number[]} candies |
| 23 | + * @param {number[][]} keys |
| 24 | + * @param {number[][]} containedBoxes |
| 25 | + * @param {number[]} initialBoxes |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var maxCandies = function(status, candies, keys, containedBoxes, initialBoxes) { |
| 29 | + let totalCandies = 0; |
| 30 | + const queue = [...initialBoxes]; |
| 31 | + const availableKeys = new Set(); |
| 32 | + const unopenedBoxes = new Set(); |
| 33 | + |
| 34 | + while (queue.length) { |
| 35 | + const currentBox = queue.shift(); |
| 36 | + |
| 37 | + if (status[currentBox]) { |
| 38 | + totalCandies += candies[currentBox]; |
| 39 | + for (const key of keys[currentBox]) availableKeys.add(key); |
| 40 | + for (const box of containedBoxes[currentBox]) queue.push(box); |
| 41 | + } else { |
| 42 | + unopenedBoxes.add(currentBox); |
| 43 | + } |
| 44 | + |
| 45 | + for (const box of unopenedBoxes) { |
| 46 | + if (availableKeys.has(box)) { |
| 47 | + status[box] = 1; |
| 48 | + unopenedBoxes.delete(box); |
| 49 | + queue.push(box); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return totalCandies; |
| 55 | +}; |
0 commit comments