I got this problem in an off-campus round, someone please help me solve the problem:
You are given N elements, each having unique values. If you distribute them among 2 children in such a way that the total unique value that each child receives must be greater than K. How many ways can you distribute the elements so that the mentioned condition holds true?
Since the answer can be very large print it modulo 1e9+7.
1 <= N <= 10^3
1 <= K <= 10^5
1 <= A[i] <= 10^9
Sample Input:
3 5
3 7 4
Sample Output:
2 -> {3,4},{7} and {7},{3,4}
I think this should work.
Let $$$y$$$ be the number of subsets of $$$A$$$ with sum at most $$$K$$$. You can compute this by $$$dp_{i,j} = $$$ number of subsets of $$$0..i$$$ with sum equal to $$$j$$$ in $$$O(NK)$$$.
Then the solution is $$$max(0, 2^N - 2y)$$$.
I'm assuming we can't skip any element from both sets. Then, we know that each person should get at least total of $$$K+1$$$. So, the sum of the array should be $$$ \ge 2 \cdot (K+1) $$$. If not, the answer is 0.
If it's possible, then we need to count the number of subsets of the given array having sum $$$ \le K $$$. Let it be $$$X$$$. Then the answer is $$$2^{n}-2 \cdot X $$$.
We can count the number of subsets having sum $$$ \le K $$$ using $$$O( N \cdot K ) $$$ time and $$$O(K)$$$ space using DP.
$$$ dp[i][j] = dp[i-1][j] + dp[i-1][j-A[i]] $$$, $$$ 1 \le i \le n $$$ , $$$ 0 \le j \le K $$$.
Below is the function:
BUT PLEASE DON'T CHEAT IN PLACEMENT EXAMS.
Wow cheating. This question was asked 9 months ago. Really cool! I've never seen an exam running for 9 months straight.
Hey, the constraints seem too tight for an O(NK) solution to pass. Anyone has a faster approach?
O(NK) is enough to pass, 10^8 operations usually equates to about 1 second of runtime. When the operations are simple, which is the case with dps usually it's usually much less.