#2079

Watering Plants

Medium
ArraySimulationSimulationGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach efficiently tracks the water needed and minimizes unnecessary trips to the river. We only return to refill when necessary, keeping track of the water left in the can.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize total steps and current water.
  2. 2Step 2: Iterate through each plant, updating steps and current water.
  3. 3Step 3: If current water is insufficient for the next plant, calculate the steps to return to the river and refill.
solution.py10 lines
1def wateringPlants(plants, capacity):
2    steps = 0
3    current_water = capacity
4    for i in range(len(plants)):
5        if current_water < plants[i]:
6            steps += (i + 1)  # Return to river
7            current_water = capacity
8        steps += 1  # Watering the plant
9        current_water -= plants[i]
10    return steps + len(plants)  # Add steps to return to river after last plant

Complexity note: The optimal solution runs in O(n) time because we only traverse the list of plants once, making decisions based on the current water level.

  • 1Always check if you need to refill before watering the next plant.
  • 2Minimize trips to the river by tracking the current water level.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.