Mid/SeniorArraySimulation

Watering Plants

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 i^th plant is located at x = i. There is a river at x = -1 where you can refill your watering can.

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 i^th plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.

Example 1
Inputplants = [2,2,3,3], capacity = 5
Output14
Following the required watering and refill rules, the steps are 1 + 1 + 2 + 3 + 3 + 4 = 14.
Example 2
Inputplants = [1,1,1,4,2,3], capacity = 4
Output30
Following the required watering and refill rules, the steps are 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.

Constraints

  • n == plants.length
  • 1 <= n <= 1000
  • 1 <= plants[i] <= 10^6
  • max(plants[i]) <= capacity <= 10^9

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate