Similar Problems

Similar Problems not available

Watering Plants - Leetcode Solution

Companies:

LeetCode:  Watering Plants Leetcode Solution

Difficulty: Medium

Topics: array simulation  

Problem Description:

You have N pots of plants which are filled with water to different levels. You want to water the plants using a watering pail. The watering pail has a fixed capacity of K liters per turn. You need to water the plants in the minimum number of turns while not wasting any water. For watering a plant, the watering pail must contain sufficient water to fill that plant.

Solution:

The solution to this problem can be solved using a binary search where we try to find the minimum number of turns required to water all plants without wasting any water. We can find the minimum turn using binary search where we try to find the capacity of watering pail for each turn.

The minimum capacity of watering pail required per turn is the maximum of the water required for any plant. Similarly, the maximum capacity of watering pail required per turn is the sum of the water required for all plants. This can be calculated by taking the sum of all water levels in the pots.

We can start with minimum capacity as the maximum of the water required for any plant and the maximum capacity as the sum of all water levels in the pots. We keep on checking if the mid is the possible capacity of the watering pail, and if yes, we try to minimize the result.

If the mid is not possible, we increase the minimum capacity, else we try to reduce the maximum capacity. We can keep changing the values of the minimum and maximum capacity until we find the minimum number of turns required to water all plants without wasting any water.

Code:

public int minDays(int[] bloomDay, int m, int k) { if (m * k > bloomDay.length) { // check if it is possible to water all plants in given no. of days return -1; } int low = Integer.MAX_VALUE, high = 0; for (int i = 0; i < bloomDay.length; i++) { // find min and max value of bloomDay low = Math.min(low, bloomDay[i]); high = Math.max(high, bloomDay[i]); } while (low < high) { // apply binary search int mid = low + (high - low) / 2; int count = 0, flowers = 0; for (int i = 0; i < bloomDay.length; i++) { if (bloomDay[i] > mid) { flowers = 0; } else if (++flowers == k) { // check if k consecutive flowers can be watered count++; flowers = 0; } } if (count >= m) { high = mid; } else { low = mid + 1; } } return low; }

Time Complexity:

The time complexity of the binary search algorithm used for solving the "Watering Plants" problem is O(N * log(max(bloomDay))) where N is the number of pots and max(bloomDay) is the maximum bloom day required to water all plants.

Space Complexity:

The space complexity of this algorithm is O(1) since we are not using any extra data structure in our implementation and only variables are created during the execution of the function.

Watering Plants Solution Code

1