g1601_1700.s1655_distribute_repeating_integers.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g1601_1700.s1655_distribute_repeating_integers;
// #Hard #Array #Dynamic_Programming #Bit_Manipulation #Backtracking #Bitmask
// #2022_04_23_Time_7_ms_(94.23%)_Space_75.4_MB_(73.08%)
import java.util.Arrays;
/**
* 1655 - Distribute Repeating Integers\.
*
* Hard
*
* 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_.
*
* **Example 1:**
*
* **Input:** nums = [1,2,3,4], quantity = [2]
*
* **Output:** false
*
* **Explanation:** The 0th customer cannot be given two different integers.
*
* **Example 2:**
*
* **Input:** nums = [1,2,3,3], quantity = [2]
*
* **Output:** true
*
* **Explanation:** The 0th customer is given [3,3]. The integers [1,2] are not used.
*
* **Example 3:**
*
* **Input:** nums = [1,1,2,2], quantity = [2,2]
*
* **Output:** true
*
* **Explanation:** The 0th customer is given [1,1], and the 1st customer is given [2,2].
*
* **Constraints:**
*
* * `n == nums.length`
* * 1 <= n <= 105
* * `1 <= nums[i] <= 1000`
* * `m == quantity.length`
* * `1 <= m <= 10`
* * 1 <= quantity[i] <= 105
* * There are at most `50` unique values in `nums`.
**/
public class Solution {
public boolean canDistribute(int[] nums, int[] quantity) {
int[] counter = count(nums);
Arrays.sort(quantity);
return dfs(counter, quantity, quantity.length - 1);
}
private boolean dfs(int[] counter, int[] quantity, int quantityId) {
if (quantityId < 0) {
return true;
}
for (int i = 0; i < counter.length; i++) {
if (i > 0 && counter[i] == counter[i - 1]) {
continue;
}
if (counter[i] >= quantity[quantityId]) {
counter[i] -= quantity[quantityId];
if (dfs(counter, quantity, quantityId - 1)) {
return true;
}
counter[i] += quantity[quantityId];
}
}
return false;
}
private int[] count(int[] nums) {
int[] counter = new int[1001];
for (int n : nums) {
counter[n]++;
}
Arrays.sort(counter);
return Arrays.copyOfRange(counter, counter.length - 50, counter.length);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy