LeetCode-in-Java

2079. Watering Plants

Medium

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:

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.

Example 1:

Input: plants = [2,2,3,3], capacity = 5

Output: 14

Explanation: Start at the river with a full watering can:

Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.

Example 2:

Input: plants = [1,1,1,4,2,3], capacity = 4

Output: 30

Explanation: Start at the river with a full watering can:

Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.

Example 3:

Input: plants = [7,7,7,7,7,7,7], capacity = 8

Output: 49

Explanation: You have to refill before watering each plant.

Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.

Constraints:

Solution

public class Solution {
    public int wateringPlants(int[] plants, int capacity) {
        int initial = capacity;
        int ans = 0;
        for (int i = 0; i < plants.length; i++) {
            if (plants[i] <= capacity) {
                ++ans;
                capacity -= plants[i];
            } else {
                ans += i;
                capacity = initial;
                ans += i + 1;
                capacity -= plants[i];
            }
        }
        return ans;
    }
}