#2105

Watering Plants II

specialist · 930 · lc medium +32 · verified · 48.6% accepted · 316 likes · top 35%

Description

Alice and Bob are watering n plants arranged in a row, labeled 0 to n - 1. Each plant requires a specific amount of water. Alice starts from the left (plant 0) and Bob starts from the right (plant n - 1); both move toward the center simultaneously.

Watering follows these rules:

- Alice waters plants left to right and Bob waters plants right to left. Both start with full cans.

- Every plant takes the same amount of time to water regardless of how much water it needs.

- A person must water the plant if they have enough water; otherwise, they refill their can instantly before watering.

- If both Alice and Bob arrive at the same plant, the one with more water in their can waters it. If they have equal water, Alice waters it.

Given a 0-indexed integer array plants of n integers, where plants[i] is the water needed by plant i, and two integers capacityA and capacityB representing the can capacities, return the total number of times they must refill their cans.

Example 1:

Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5
Output: 1
Explanation:
- Initially, Alice and Bob have 5 units of water each in their watering cans.
- Alice waters plant 0, Bob waters plant 3.
- Alice and Bob now have 3 units and 2 units of water respectively.
- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.
So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.

Example 2:

Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4
Output: 2
Explanation:
- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.
- Alice waters plant 0, Bob waters plant 3.
- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.
- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.
So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.

Example 3:

Input: plants = [5], capacityA = 10, capacityB = 8
Output: 0
Explanation:
- There is only one plant.
- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.
So, the total number of times they have to refill is 0.

Code

1
2
3