Leetcode 2105: Watering Plants II

grid47
grid47
Exploring patterns and algorithms
Apr 10, 2024 9 min read

Alice and Bob are tasked with watering a garden of n plants. The plants are arranged in a row and need varying amounts of water. Alice waters the plants from left to right, while Bob waters them from right to left. They both begin with full watering cans. If they don’t have enough water for the next plant, they refill their cans. In case they both reach the same plant, the one with more water in their can should water the plant, or Alice waters it in case of a tie. The goal is to determine how many times Alice and Bob have to refill their cans to water all the plants.
Problem
Approach
Steps
Complexity
Input: You are given a 0-indexed integer array, plants, where each element represents the amount of water a corresponding plant needs. Additionally, two integers, capacityA and capacityB, represent the capacities of Alice’s and Bob’s watering cans, respectively.
Example: plants = [3, 2, 5, 4], capacityA = 6, capacityB = 6
Constraints:
• 1 <= plants.length <= 10^5
• 1 <= plants[i] <= 10^6
• max(plants[i]) <= capacityA, capacityB <= 10^9
Output: Return the number of times Alice and Bob need to refill their watering cans in order to water all the plants.
Example: For plants = [3, 2, 5, 4], capacityA = 6, capacityB = 6, the output is 2.
Constraints:
Goal: The goal is to efficiently compute the number of refills required by simulating the watering process while tracking the remaining water in Alice's and Bob's cans.
Steps:
• Initialize two pointers, one for Alice starting from the left (i = 0) and one for Bob starting from the right (j = n - 1).
• Initialize counters for Alice's and Bob's current water levels (alice, bob) with the respective capacities.
• Simulate the process of watering plants for both Alice and Bob, adjusting the number of refills as needed.
• If either Alice or Bob runs out of water for their current plant, they refill their can and continue watering.
Goal: The problem involves a large input size (up to 10^5 plants), and the amount of water required by each plant can be as large as 10^6.
Steps:
• The number of plants (n) can be up to 10^5.
• Each plant's water requirement can be as large as 10^6.
• The capacities of Alice and Bob’s cans can be as large as 10^9.
Assumptions:
• Alice and Bob always start with full watering cans.
• Alice waters the plants from left to right, and Bob waters the plants from right to left.
Input: Example 1: plants = [3, 2, 5, 4], capacityA = 6, capacityB = 6
Explanation: Initially, both Alice and Bob have 6 units of water. Alice waters plant 0 (3 units), leaving 3 units in her can. Bob waters plant 3 (4 units), leaving 2 units in his can. Alice then waters plant 1 (2 units), leaving 1 unit in her can, and Bob refills and waters plant 2 (5 units), leaving 1 unit in his can. Total refills = 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus