Skip to content

Commit 82aa211

Browse files
committed
Runtime: 6 ms (Top 61.19%) | Memory: 57.10 MB (Top 59.7%)
1 parent 125688b commit 82aa211

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Runtime: 6 ms (Top 61.19%) | Memory: 57.10 MB (Top 59.7%)
2+
3+
class Solution {
4+
public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes)
5+
{
6+
int n=initialBoxes.length;
7+
8+
if(n==0)
9+
return 0;
10+
11+
Queue<Integer> q=new LinkedList<>();
12+
int totalCandies=0;
13+
14+
for(int i:initialBoxes)
15+
{
16+
if(status[i]==0)
17+
{
18+
q.add(i);
19+
}
20+
else
21+
{
22+
totalCandies+=candies[i]; // Add all Candies of intial box;
23+
for(int j=0;j<containedBoxes[i].length;j++)
24+
{
25+
q.add(containedBoxes[i][j]); // Add all Contained Boxes in queue;
26+
}
27+
for(int j=0;j<keys[i].length;j++)
28+
{
29+
status[keys[i][j]]=1; // Set status of of box=1 if we found key;
30+
}
31+
}
32+
}
33+
34+
while(q.size()>0 && isValid(q,status))
35+
{
36+
int b=q.poll();
37+
if(status[b]==1)
38+
{
39+
totalCandies+=candies[b]; // Add all Candies of selected box;
40+
41+
42+
for(int j=0;j<containedBoxes[b].length;j++)
43+
{
44+
q.add(containedBoxes[b][j]); // Add all Contained Boxes in queue;
45+
}
46+
for(int j=0;j<keys[b].length;j++)
47+
{
48+
status[keys[b][j]]=1; // Set status of of box=1 if we found key;
49+
}
50+
}
51+
else
52+
q.add(b); // If Status==0 add again in queue;
53+
}
54+
return totalCandies;
55+
}
56+
57+
/* This function helps to know whether any boxes in queue status is still open or not
58+
if all boxes status is off then it will return false and above while loop while terminate beacue now we cannot get any candy*/
59+
public boolean isValid(Queue<Integer> q,int[] status)
60+
{
61+
Queue<Integer> cq=new LinkedList<>(q);
62+
63+
while(cq.size()>0)
64+
{
65+
if(status[cq.poll()]==1)
66+
return true;
67+
}
68+
return false;
69+
}
70+
}

0 commit comments

Comments
 (0)