[LeetCode] Distribute Repeating Integers

1655. Distribute Repeating Integers

You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:

  • The ith customer gets exactly quantity[i] integers,
  • The integers the ith customer gets are all equal, and
  • Every customer is satisfied.

Return true if it is possible to distribute nums according to the above conditions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
bool helper(map<int,int>& rCounts, vector<int>& q, int p) {
if(p == q.size()) return true;
for(auto it = rCounts.lower_bound(q[p]); it != end(rCounts); it++) {
int count = it->first;
int left = it->second;
if(!left) continue;
rCounts[count - q[p]]++;
rCounts[count]--;
if(helper(rCounts,q,p + 1))
return true;
rCounts[count]++;
rCounts[count - q[p]]--;
}

return false;
}
public:
bool canDistribute(vector<int>& nums, vector<int>& quantity) {
unordered_map<int, int> counter;
map<int, int> rCounts;
for(auto n : nums) counter[n]++;
for(auto [k, v] : counter) rCounts[v]++;
sort(quantity.begin(), quantity.end(), greater<int>());

return helper(rCounts, quantity, 0);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/10/PS/LeetCode/distribute-repeating-integers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.