2-D Dynamic Programming Knapsack
554. Count Partitions with a Given Difference
You are given an array of non-negative integers arr and an integer d. Split the elements into two groups,
S1 and S2, so that every element goes into exactly one group. A group may be empty.
Return the number of splits where the sum of S1 minus the sum of S2 is exactly d. Two splits are different if
some element is in a different group, even when elements have equal values or are 0.
The number can be very large, so return it modulo 109 + 7.
Example 1
Input: arr = [1, 3, 2, 4, 2], d = 4
3Explanation: S2 holds [4], [1, 3] or the two 2s, and S1 holds the rest. In each split S1 sums to 8 and S2 sums to 4.
Example 2
Input: arr = [0, 3, 0, 3], d = 0
8Explanation: Each group must hold one 3, and either 3 can go in S1, which gives 2 splits. Each 0 can go in either group too, so there are 2 × 2 × 2 = 8 splits.
Example 3
Input: arr = [4, 1, 2], d = 2
0Explanation: The total is 7, so every split gives an odd difference, and no split gives 2.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ arr.length ≤ 10000 ≤ arr[i] ≤ 104sum(arr) ≤ 2 × 1040 ≤ d ≤ sum(arr)
Clarifying questions
What you would ask an interviewer before writing any code.