Count partitions with given difference

Dynamic Programming DP on subsequences Hard
  • This problem and its underlying concept of dynamic programming is a fundamental part of many algorithms used in machine learning and data analysis
  • For instance, these types of partitioning problems are often used in dividing datasets for testing and training purposes, in a way that a certain condition is met - be it the difference between sums of subsets, or maximizing the similarity of data within each subset
  • Additionally, it is also common in load balancing problems where tasks are distributed across different servers in a way that the workload difference between any two servers is minimum

Given an array arr of n integers and an integer diff, count the number of ways to partition the array into two subsets such that the absolute difference between their sums is equal to diff. Return the result modulo 109+7.

Examples:

Input: arr = [1, 1, 2, 3], diff = 1

Output: 3

Explanation: The subsets are [1, 2] and [1, 3], [1, 3] and [1, 2], [1, 1, 2] and [3].

Input: arr = [1, 2, 3, 4], diff = 2

Output: 2

Explanation: The subsets are [1, 3] and [2, 4], [1, 2, 3] and [4].

Input: arr = [5, 2, 6, 4], diff = 3

Constraints

  • 1 <= n <= 200
  • 0 <= d <= 104
  • 0 <= arr[i] <= 50

Hints

  • "the problem reduces to finding the number of subsets whose sum is S1. If S + diff is odd, no valid partition exists → return 0. Otherwise, find count of subsets that sum to S1 using Subset Sum Count DP."
  • We use a 1D DP array (dp[j]) where dp[j] represents the number of ways to achieve sum j. We iterate in reverse (j = S1 to arr[i]) to avoid duplicate counting.

Company Tags

Zoho Teladoc Health Ernst & Young Roblox KPMG Epic Games Databricks Deloitte Instacart Intel Seagate Technology Micron Technology Electronic Arts Docker Rakuten Goldman Sachs Snowflake Medtronic Philips Healthcare JPMorgan Chase Unity Technologies Boston Consulting Group Ubisoft Walmart Square Google Microsoft Amazon Meta Apple Netflix Adobe