|
| 1 | +/** |
| 2 | + * 1655. Distribute Repeating Integers |
| 3 | + * https://leetcode.com/problems/distribute-repeating-integers/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array of n integers, nums, where there are at most 50 unique values in |
| 7 | + * the array. You are also given an array of m customer order quantities, quantity, where |
| 8 | + * quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible |
| 9 | + * to distribute nums such that: |
| 10 | + * - The ith customer gets exactly quantity[i] integers, |
| 11 | + * - The integers the ith customer gets are all equal, and |
| 12 | + * - Every customer is satisfied. |
| 13 | + * |
| 14 | + * Return true if it is possible to distribute nums according to the above conditions. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} nums |
| 19 | + * @param {number[]} quantity |
| 20 | + * @return {boolean} |
| 21 | + */ |
| 22 | +var canDistribute = function(nums, quantity) { |
| 23 | + const frequencyMap = new Map(); |
| 24 | + for (const num of nums) { |
| 25 | + frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1); |
| 26 | + } |
| 27 | + |
| 28 | + const frequencies = Array.from(frequencyMap.values()).sort((a, b) => b - a); |
| 29 | + quantity.sort((a, b) => b - a); |
| 30 | + |
| 31 | + return canSatisfy(0, frequencies); |
| 32 | + |
| 33 | + function canSatisfy(index, counts) { |
| 34 | + if (index === quantity.length) return true; |
| 35 | + |
| 36 | + for (let i = 0; i < counts.length; i++) { |
| 37 | + if (counts[i] >= quantity[index]) { |
| 38 | + counts[i] -= quantity[index]; |
| 39 | + if (canSatisfy(index + 1, counts)) return true; |
| 40 | + counts[i] += quantity[index]; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return false; |
| 45 | + } |
| 46 | +}; |
0 commit comments