Watering Plants - Problem
You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.
Each plant needs a specific amount of water. You will water the plants in the following way:
- Water the plants in order from left to right.
- After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.
- You cannot refill the watering can early.
You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.
Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.
Input & Output
Example 1 — Basic Case
$
Input:
plants = [2,2,3,3], capacity = 5
›
Output:
14
💡 Note:
Start at river (-1) with 5 units. Go to plant 0 (+1 step), water with 2 units, 3 left. Go to plant 1 (+1 step), water with 2 units, 1 left. Can't water plant 2 (needs 3), so go back to river (+2 steps) and forward to plant 2 (+3 steps), water with 3 units, 2 left. Go to plant 3 (+1 step), can't water (needs 3), go back to river (+3 steps) and forward to plant 3 (+4 steps), water plant 3. Total: 1+1+2+3+1+3+4 = 15... wait let me recalculate: 1+1+(2+3)+1+(3+4) = 14 steps
Example 2 — No Refill Needed
$
Input:
plants = [1,1,1,1], capacity = 4
›
Output:
4
💡 Note:
Start with capacity 4. Each plant needs 1 unit. Move and water each: 1+1+1+1 = 4 steps total, no refills needed
Example 3 — Refill Every Plant
$
Input:
plants = [7], capacity = 7
›
Output:
1
💡 Note:
Single plant needs exactly our capacity. Move from river to plant 0 in 1 step, water it. Total: 1 step
Constraints
- 1 ≤ plants.length ≤ 1000
- 1 ≤ plants[i] ≤ 106
- plants[i] ≤ capacity ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Plants array [2,2,3,3] and capacity 5
2
Process
Water plants left-to-right, refill when needed
3
Output
Total steps taken including refill trips
Key Takeaway
🎯 Key Insight: Simulate the process step by step, adding refill roundtrips when water is insufficient
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code