Watering Plants
Problem
You walk along a row of plants from left to right with a full watering can of capacity. plants[i] is the water needed for plant i. If the remaining water is less than plants[i] you must walk back to the river (position -1), refill, and walk back. Every step (forward or backward) counts as 1 step. Return the total number of steps to water every plant.
plants = [2, 2, 3, 3], capacity = 514def watering_plants(plants, capacity):
steps = 0
water = capacity
for i, need in enumerate(plants):
if water < need:
steps += 2 * i
water = capacity
steps += 1
water -= need
return steps
function wateringPlants(plants, capacity) {
let steps = 0;
let water = capacity;
for (let i = 0; i < plants.length; i++) {
if (water < plants[i]) {
steps += 2 * i;
water = capacity;
}
steps += 1;
water -= plants[i];
}
return steps;
}
class Solution {
public int wateringPlants(int[] plants, int capacity) {
int steps = 0;
int water = capacity;
for (int i = 0; i < plants.length; i++) {
if (water < plants[i]) {
steps += 2 * i;
water = capacity;
}
steps += 1;
water -= plants[i];
}
return steps;
}
}
int wateringPlants(vector<int>& plants, int capacity) {
int steps = 0;
int water = capacity;
for (int i = 0; i < (int)plants.size(); i++) {
if (water < plants[i]) {
steps += 2 * i;
water = capacity;
}
steps += 1;
water -= plants[i];
}
return steps;
}
Explanation
We just simulate the walk down the row of plants, counting every step. The only decision is when we have to detour back to the river to refill.
We carry water (starting full at capacity) and a steps counter. For each plant i, if the can does not have enough for plants[i], we must walk all the way back to the river and return.
That round trip is the clever shortcut: a plant at index i sits i steps from the river, so going back and coming forward again adds exactly 2 * i steps. After the refill, water resets to capacity.
Whether or not we refilled, we then take one step onto plant i and water it, doing steps += 1 and water -= plants[i].
Example: plants = [2,2,3,3], capacity = 5. Plants 0 and 1 cost 1 step each. Plant 2 needs a refill (2*2 = 4 steps) then 1 step, plant 3 needs a refill (2*3 = 6 steps) then 1 step. Total = 14.