easyArraysPattern: Greedy
Divide Equal Quantities Solution
Problem Statement
You are given an array of integers `quantities`, determine the maximum number of groups that can be formed such that each group receives an equal number of quantities.
Examples
Example 1:
Input:[2, 4, 6, 8]
Output:2
Explanation: Divide into groups of 4 and 4 quantities, or 2 and 2 quantities with 4 groups, maximum groups formed with equal quantities is when quantities are divided into 2 groups of 4.
Example 2:
Input:[10, 10, 10, 10]
Output:4
Explanation: Maximum equal groups formed is when each quantity is in its own group.
Constraints
- 1 <= quantities.length <= 1000
- -10^5 <= quantities[i] <= 10^5
- quantities[i] must be a non-negative integer for all elements except possibly zero
- It is guaranteed that the sum of all elements in the array does not exceed 10^6
Time: O(n log m) Space: O(1)
The optimized approach involves finding the greatest common divisor (GCD) of all the quantities in the array, as this represents the largest possible group size where all groups receive an equal number of quantities. This method has a complexity of O(n log m), where n is the number of quantities and m is the maximum quantity. It allows us to efficiently determine the maximum number of groups.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
import sys
quantities = list(map(int, sys.stdin.readline().split()))
max_groups = 0
for i in range(1, max(quantities) + 1):
valid_groups = True
for j in range(len(quantities)):
if quantities[j] % i != 0:
valid_groups = False
break
if valid_groups:
max_groups = max(max_groups, min(qty // i for qty in quantities))
print(max_groups)