Watering Plants

medium array simulation

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.

Inputplants = [2, 2, 3, 3], capacity = 5
Output14
Water 0 (5→3), 1 (3→1). Can't water 2 (need 3, have 1) — walk back 2 steps, refill, walk forward 3 steps. Water 2 (5→2). Can't water 3 — walk back 3, refill, forward 4. Water 3. Total = 4 + 5 + 5 = 14.

def 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;
}
Time: O(n) Space: O(1)