Partition a set into two subsets with minimum absolute sum difference

Dynamic Programming DP on subsequences Hard
  • This problem can be challenging but it's also interesting because it's a form of 'Partitioning Problem', which is a key part of many real-world applications, such as load balancing in distributed systems or databases
  • Developers often need to partition data among different machines or database tables to balance the load and achieve maximum performance
  • The minimization of the absolute difference in sums is analogous to minimizing the difference in load between the most and least loaded machines or tables

Given an array arr of n integers, partition the array into two subsets such that the absolute difference between their sums is minimized.

Examples:

Input: arr = [1, 7, 14, 5]

Output: 1

Explanation: The array can be partitioned as [1, 7, 5] and [14], with an absolute difference of 1.

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

Output: 0

Explanation: The array can be partitioned as [3, 2, 2] and [6, 1], with an absolute difference of 0.

Input: arr = [2, 2, 2, 9]

Constraints

  • 1 ≤ n * sum of array elements ≤ 106
  • 0 < arr[i] <= 104

Hints

  • "Define DP state: dp[j] = True if there exists a subset with sum j (similar to the subset sum problem). Find the closest sum to S/2. The minimized difference is |S - 2 * j|."
  • "Since each DP state depends only on the previous row, we can optimize to O(S/2) space: Use a 1D DP array (dp[target]) updated from right to left to prevent overwriting values."

Company Tags

AMD Teladoc Health Bloomberg Chewy Square NVIDIA Seagate Technology Nutanix Medtronic Zoho Bain & Company Roblox Cloudflare Target Boston Consulting Group Epic Systems Flipkart IBM Bungie Zynga Unity Technologies Morgan Stanley Walmart HCL Technologies PwC Google Microsoft Amazon Meta Apple Netflix Adobe