Skip to content

Commit 7474eb6

Browse files
committed
Runtime: 4 ms (Top 96.18%) | Memory: 57.70 MB (Top 65.65%)
1 parent 197c1e4 commit 7474eb6

File tree

1 file changed

+42
-26
lines changed

1 file changed

+42
-26
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,48 @@
1+
// Runtime: 4 ms (Top 96.18%) | Memory: 57.70 MB (Top 65.65%)
2+
13
class Solution {
2-
public int minimumRefill(int[] plants, int capacityA, int capacityB) {
3-
int count=0;
4-
int c1=capacityA,c2=capacityB;
5-
for(int start=0,end=plants.length-1;start<=plants.length/2&&end>=plants.length/2;start++,end--){
6-
if(start==end||start>end)break;
7-
if(c1>=plants[start]){
8-
c1-=plants[start];
4+
public int minimumRefill(int[] p, int ca, int cb) {
5+
6+
int refill= 0,oca = ca, ocb = cb;// let save our orginal capacity , needed to refill can again
7+
int i=0, j = p.length-1; // starting both end
8+
9+
while(i<=j){
10+
11+
if(i==j){// mean both at same position
12+
if(ca>=cb){
13+
if(p[i]>ca){
14+
refill++;
15+
}
16+
}
17+
else{
18+
if(p[j]>cb){
19+
refill++;
20+
}
21+
}
22+
// no more plant left for watering so break loop
23+
break;
924
}
10-
else{
11-
count++;
12-
c1=capacityA;
13-
c1-=plants[start];
25+
26+
// first check if they have sufficient amount of water
27+
// if not then refill it with orginal capacity
28+
29+
if(p[i]>ca){
30+
refill++;
31+
ca = oca;
32+
}
33+
if(p[j]>cb){
34+
refill++;
35+
cb= ocb;
1436
}
15-
if(c2>=plants[end]){
16-
c2-=plants[end];
17-
}
18-
else{
19-
count++;
20-
c2=capacityB;
21-
c2-=plants[end];
22-
}
23-
}
24-
if((c1>c2||c1==c2)&&plants.length%2!=0){
25-
if(plants[plants.length/2]>c1)count++;
26-
}
27-
else if(c1<c2&&plants.length%2!=0){
28-
if(plants[plants.length/2]>c2)count++;
37+
38+
// decrease consumed water
39+
ca-=p[i] ;
40+
cb-=p[j];
41+
42+
// move both
43+
i++;
44+
j--;
2945
}
30-
return count;
46+
return refill;
3147
}
3248
}

0 commit comments

Comments
 (0)