Created
June 3, 2025 19:56
-
-
Save tatsuyax25/0d64816fb14de682e28bcb1af97e3783 to your computer and use it in GitHub Desktop.
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] i
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} status - Array indicating whether each box is open (1) or closed (0). | |
* @param {number[]} candies - Number of candies in each box. | |
* @param {number[][]} keys - List of keys contained in each box. | |
* @param {number[][]} containedBoxes - List of boxes contained in each box. | |
* @param {number[]} initialBoxes - Labels of the boxes you start with. | |
* @return {number} - Maximum number of candies you can collect. | |
*/ | |
var maxCandies = function(status, candies, keys, containedBoxes, initialBoxes) { | |
const queue = [...initialBoxes]; // Queue to process available boxes | |
const visited = new Array(status.length).fill(false); // Track visited boxes | |
const foundBoxes = new Set(); // Track unopened boxes we have found | |
const collectedKeys = new Set(); // Track keys we have collected | |
let totalCandies = 0; // Total candies collected | |
while (queue.length > 0) { | |
const boxNumber = queue.shift(); // Process the next available box | |
// If we have already visited this box, skip it | |
if (visited[boxNumber]) continue; | |
// If the box is closed and we don't have the key, store it and continue | |
if (status[boxNumber] === 0 && !collectedKeys.has(boxNumber)) { | |
foundBoxes.add(boxNumber); | |
continue; | |
} | |
// Mark the box as visited | |
visited[boxNumber] = true; | |
// Collect all candies inside the box | |
totalCandies += candies[boxNumber]; | |
// Collect any new keys from this box | |
for (const key of keys[boxNumber]) { | |
collectedKeys.add(key); | |
// If we previously found a box but didn't have the key, unlock it now | |
if (foundBoxes.has(key)) { | |
queue.push(key); | |
foundBoxes.delete(key); | |
} | |
} | |
// Add any new boxes found inside this one | |
for (const newBox of containedBoxes[boxNumber]) { | |
queue.push(newBox); | |
} | |
} | |
return totalCandies; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment