VOOZH about

URL: https://www.geeksforgeeks.org/dsa/geeks-plants/

⇱ Geek's Plants - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Geek's Plants

Last Updated : 23 Jul, 2025

Geek wants to water n plants (numbered from 0 to n-1), where planti requires arr[i] units of water daily. Geek has to use buckets of the same size and can not use a bucket more than once a day. Also, Geek does not waste any water. Find the minimum number of buckets Geek needs to use daily for watering the plants.

Note: Each bucket can be designated for only one plant after receiving a fresh refill of water at the beginning of each day.

Examples:

Input: N = 4, arr[] = {2, 6, 4, 10}
Output: 11
Explanation: Geek will use buckets of size 2 units daily. Then Geek will need 1, 3, 2, and 5 numbers of buckets for plant 0, plant 1, plant 2, and plant 3 respectively daily.

Input: N = 1, arr[] = {5}
Output: 1
Explanation: Geek will use a bucket of size 5 units daily. Then Geek will need 1 bucket for plant 0 daily.

Approach:

Since all bucket sizes should be the same, and one bucket is used for only one plant, we can deduce that the bucket size should be the common divisor of all elements in the array. As we need to determine the minimum number of buckets required for watering all the plants, we will calculate the greatest common divisor (GCD) of all the elements in the array.

Steps to solve this problem:

Initially, we take one variable named gcd_val to store the greatest common divisor of all elements of the array. It is initialized by the value 0.

  • Using a loop, we will traverse the given array and, for each element of the array, we will calculate its GCD using the Euclidean Algorithm. In the C++ language, we can use a built-in function(i.e. __gcd(a,b)) for calculating GCD.
  • Now, we have taken another variable called ans to store the answer to the problem. Initially, the value of the variable is 0.
  • Now, for every element of the array, we will divide each element of the array by the value stored inside the gcdval variable, and the division result will be added to the answer variable, ans.
  • Finally, we will return the ans variable as an answer, i.e., the minimum number of buckets required for watering the plants.

Below is the implementation of the above approach.


Output
Minimum number of buckets required: 11

Time Complexity: O(N*logP)
Auxiliary Space: O(1)

Comment
Article Tags: