Suppose we have an array nums, there are at most 50 unique values. We also have another array called quantity, where quantity[i] denotes the amount of values the ith customer ordered.We have to check whether it is possible to distribute nums such that
The ith customer gets exactly quantity[i] items,
The value that the ith customer gets are all equal, and
All customers are satisfied.
So, if the input is like nums = [5,1,2,2,3,4,4,3,3] quantity = [2,2,3], then the output will be True because two customer wants two elements each, so they can get [2,2] and [4,4], and the third one wants three items, they can get [3,3,3], so all are satisfied.
To solve this, we will follow these steps −
Define a function util() . This will take i, cntr
if i is same as size of quantity , then
return True
temp_counter := make a copy of cntr
for each cnt in cntr, do
if cnt >= quantity[i], then
temp_counter[cnt] := temp_counter[cnt] - 1
if temp_counter[cnt] is same as 0, then
delete cnt-th element from temp_counter
rem := cnt - quantity[i]
temp_counter[rem] := temp_counter[rem] + 1
if util(i+1, temp_counter) is true, then
return True
temp_counter[rem] := temp_counter[rem] - 1
if temp_counter[rem] is same as 0, then
delete rem-th element from temp_counter
temp_counter[cnt] := temp_counter[cnt] + 1
return False
From the main method, do the following
cnt := map holding frequency of all frequencies of numbers present in nums
sort quantity in reverse order
return util(0, cnt)
Example
Let us see the following implementation to get better understanding
from collections import Counter def solve(nums, quantity): def util(i, cntr): if i == len(quantity): return True temp_counter = cntr.copy() for cnt in cntr: if cnt >= quantity[i]: temp_counter[cnt] -= 1 if temp_counter[cnt] == 0: temp_counter.pop(cnt) rem = cnt - quantity[i] temp_counter[rem] += 1 if util(i+1, temp_counter): return True temp_counter[rem] -= 1 if temp_counter[rem] == 0: temp_counter.pop(rem) temp_counter[cnt] += 1 return False cnt = Counter(Counter(nums).values()) quantity.sort(reverse=True) return util(0, cnt) nums = [5,1,2,2,3,4,4,3,3] quantity = [2,2,3] print(solve(nums, quantity))
Input
[0,1,2,3,4], [[3,1],[1,3],[5,6]]
Output
True