Maximum Candies You Can Get from Boxes LeetCode solution in Java

1
class Solution {
2
public int maxCandies(
3
int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
4
int n = initialBoxes.length;
5

6
if (n == 0) return 0;
7

8
Queue<Integer> q = new LinkedList<>();
9
int totalCandies = 0;
10

11
for (int i : initialBoxes) {
12
if (status[i] == 0) {
13
q.add(i);
14
} else {
15
totalCandies += candies[i]; // Add all Candies of intial box;
16
for (int j = 0; j < containedBoxes[i].length; j++) {
17
q.add(containedBoxes[i][j]); // Add all Contained Boxes in queue;
18
}
19
for (int j = 0; j < keys[i].length; j++) {
20
status[keys[i][j]] = 1; // Set status of of box=1 if we found key;
21
}
22
}
23
}
24

25
while (q.size() > 0 && isValid(q, status)) {
26
int b = q.poll();
27
if (status[b] == 1) {
28
totalCandies += candies[b]; // Add all Candies of selected box;
29

30
for (int j = 0; j < containedBoxes[b].length; j++) {
31
q.add(containedBoxes[b][j]); // Add all Contained Boxes in queue;
32
}
33
for (int j = 0; j < keys[b].length; j++) {
34
status[keys[b][j]] = 1; // Set status of of box=1 if we found key;
35
}
36
} else q.add(b); // If Status==0 add again in queue;
37
}
38
return totalCandies;
39
}
40

41
/* This function helps to know whether any boxes in queue status is still open or not
42
if all boxes status is off then it will return false and above while loop while terminate beacue now we cannot get any candy*/
43
public boolean isValid(Queue<Integer> q, int[] status) {
44
Queue<Integer> cq = new LinkedList<>(q);
45

46
while (cq.size() > 0) {
47
if (status[cq.poll()] == 1) return true;
48
}
49
return false;
50
}
51
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0