Skip to content

Commit 3e22a0d

Browse files
authored
Create watering-plants-ii.cpp
1 parent 2c83185 commit 3e22a0d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

C++/watering-plants-ii.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int minimumRefill(vector<int>& plants, int capacityA, int capacityB) {
7+
int result = 0 ;
8+
int left = 0, right = size(plants) - 1;
9+
int canA = capacityA, canB = capacityB;
10+
while (left < right) {
11+
if (canA < plants[left]) {
12+
++result;
13+
canA = capacityA;
14+
}
15+
canA -= plants[left++];
16+
if (canB < plants[right]) {
17+
++result;
18+
canB = capacityB;
19+
}
20+
canB -= plants[right--];
21+
}
22+
if (left == right) {
23+
if (max(canA, canB) < plants[left]) {
24+
++result;
25+
}
26+
}
27+
return result;
28+
}
29+
};

0 commit comments

Comments
 (0)