oneby7

2-D Dynamic Programming Knapsack

554. Count Partitions with a Given Difference

Medium

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

Output: 3

Explanation: 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

Output: 8

Explanation: 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

Output: 0

Explanation: 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.

arr = [0, 3, 1, 2], d = 2

Constraints

  • 1 ≤ arr.length ≤ 1000
  • 0 ≤ arr[i] ≤ 104
  • sum(arr) ≤ 2 × 104
  • 0 ≤ d ≤ sum(arr)

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.