LeetCode 2105: Watering Plants II Solution
Master LeetCode problem 2105 (Watering Plants II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2105. Watering Plants II
Problem Explanation
Explanation:
- We can simulate the watering process of Alice and Bob by iterating over the plants array from both ends.
- We keep track of the current water levels of Alice and Bob.
- If either Alice or Bob does not have enough water to water a plant, they refill their watering can and continue.
- We count the number of refills needed to water all the plants.
Time Complexity: O(n)
Space Complexity: O(1)
:
Solution Code
class Solution {
public int minRefills(int[] plants, int capacityA, int capacityB) {
int n = plants.length;
int refills = 0;
int left = 0, right = n - 1;
int waterA = capacityA, waterB = capacityB;
while (left <= right) {
if (waterA < plants[left]) {
waterA = capacityA;
refills++;
} else {
waterA -= plants[left];
left++;
}
if (left <= right && waterB < plants[right]) {
waterB = capacityB;
refills++;
} else {
if (left <= right) {
waterB -= plants[right];
right--;
}
}
}
return refills;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2105 (Watering Plants II)?
This page provides optimized solutions for LeetCode problem 2105 (Watering Plants II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2105 (Watering Plants II)?
The time complexity for LeetCode 2105 (Watering Plants II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2105 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2105 in Java, C++, or Python.