LeetCode 2079: Watering Plants Solution

Master LeetCode problem 2079 (Watering Plants), 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.

2079. Watering Plants

Problem Explanation

Explanation

To solve this problem efficiently, we can simulate the process of watering the plants while keeping track of the steps taken. We start at the river with a full watering can, then iterate through the plants from left to right. For each plant, we check if we have enough water in the can to water it completely. If not, we return to the river to refill the can and continue watering the remaining plants.

Algorithm

  1. Initialize variables steps to 0, currWater to the capacity, and currPos to -1 (indicating the river).
  2. Iterate through the plants: a. Calculate the steps needed to water the current plant. b. If currWater is not enough, return to the river and refill the can, updating steps. c. Water the current plant and update currWater.
  3. Return the total steps taken.

Time Complexity

The time complexity of this algorithm is O(n) where n is the number of plants.

Space Complexity

The space complexity of this algorithm is O(1) as we are using only a constant amount of extra space.

Solution Code

class Solution {
    public int minSteps(int[] plants, int capacity) {
        int steps = 0;
        int currWater = capacity;
        int currPos = -1;
        
        for (int plant : plants) {
            int stepsNeeded = Math.abs(currPos - plant) + 1;
            
            if (stepsNeeded > currWater) {
                steps += Math.abs(currPos - (-1)) + 1; // return to river
                currWater = capacity;
            }
            
            steps += stepsNeeded;
            currWater -= stepsNeeded;
            currPos = plant;
        }
        
        return steps;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2079 (Watering Plants)?

This page provides optimized solutions for LeetCode problem 2079 (Watering Plants) 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 2079 (Watering Plants)?

The time complexity for LeetCode 2079 (Watering Plants) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2079 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2079 in Java, C++, or Python.

Back to LeetCode Solutions