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 exactlyquantity[i] integers,
The integers the ith customer gets are all equal, and
Every customer is satisfied.
Return trueif it is possible to distributenumsaccording to the above conditions.
We use bitmask DP to represent which customers have been satisfied. For each unique integer, we try all possible subsets of unsatisfied customers that can be satisfied with the available count. We update the DP accordingly.
classSolution {
public:bool canDistribute(vector<int>& nums, vector<int>& quantity) {
unordered_map<int, int> freq;
for (int x : nums) freq[x]++;
vector<int> counts;
for (auto& [k, v] : freq) counts.push_back(v);
int m = quantity.size(), n = counts.size();
vector<bool> dp(1<<m);
dp[0] = true;
for (int c : counts) {
vector<bool> ndp = dp;
for (int mask =0; mask < (1<<m); ++mask) {
if (!dp[mask]) continue;
for (int sub = ((1<<m)-1)^mask; sub; sub = (sub-1)&(((1<<m)-1)^mask)) {
int sum =0;
for (int i =0; i < m; ++i) if (sub & (1<<i)) sum += quantity[i];
if (sum <= c) ndp[mask|sub] = true;
}
}
dp = ndp;
}
return dp[(1<<m)-1];
}
};
classSolution {
publicbooleancanDistribute(int[] nums, int[] quantity) {
Map<Integer, Integer> freq =new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);
List<Integer> counts =new ArrayList<>(freq.values());
int m = quantity.length, n = counts.size();
boolean[] dp =newboolean[1<<m];
dp[0]=true;
for (int c : counts) {
boolean[] ndp = dp.clone();
for (int mask = 0; mask < (1<<m); ++mask) {
if (!dp[mask]) continue;
for (int sub = ((1<<m)-1)^mask; sub > 0; sub = (sub-1)&(((1<<m)-1)^mask)) {
int sum = 0;
for (int i = 0; i < m; ++i) if ((sub & (1<<i)) > 0) sum += quantity[i];
if (sum <= c) ndp[mask|sub]=true;
}
}
dp = ndp;
}
return dp[(1<<m)-1];
}
}
classSolution {
funcanDistribute(nums: IntArray, quantity: IntArray): Boolean {
val freq = nums.groupingBy { it }.eachCount()
val counts = freq.values.toList()
val m = quantity.size
var dp = BooleanArray(1 shl m)
dp[0] = truefor (c in counts) {
val ndp = dp.copyOf()
for (mask in0 until (1 shl m)) {
if (!dp[mask]) continuevar sub = ((1 shl m) - 1) xor mask
while (sub > 0) {
var sum = 0for (i in0 until m) if ((sub and (1 shl i)) > 0) sum += quantity[i]
if (sum <= c) ndp[mask or sub] = true sub = (sub - 1) and (((1 shl m) - 1) xor mask)
}
}
dp = ndp
}
return dp[(1 shl m) - 1]
}
}