Count subsets with sum K

Dynamic Programming DP on subsequences Hard
  • An interesting real-world application of this problem can be found in the development of algorithms for financial portfolio management systems
  • These systems must often identify subsets of stocks (from a larger pool) that sum to a specific target value
  • This allows fund managers to balance their portfolios for risk and return
  • Counting the number of such subsets can be a part of the process to identify multiple possibilities for optimal portfolio constructions based on different risk-return preferences

Given an array arr of n integers and an integer K, count the number of subsets of the given array that have a sum equal to K. Return the result modulo 109+7.

Examples:

Input: arr = [2, 3, 5, 16, 8, 10], K = 10


Output: 3


Explanation: The subsets are [2, 8], [10], and [2, 3, 5].

Input: arr = [1, 2, 3, 4, 5], K = 5


Output: 3


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

Input: arr = [2, 2, 2, 2], K = 4

Constraints

  •  1 <= n <= 100
  • 1 <= arr[i] <= 103
  • 1 <= K <= 103

Hints

  • "Define dp[i][j] as the number of ways to form sum j using the first i elements of arr. If we exclude arr[i], then dp[i][j] = dp[i-1][j]. If we include arr[i], then dp[i][j] = dp[i-1][j - arr[i]] (if j ≥ arr[i])."
  • "ince dp[i][j] depends only on dp[i-1][j] and dp[i-1][j - arr[i]], we can optimize to O(K) space by using a 1D DP array (dp[K]) updated from right to left: dp[j]=(dp[j]+dp[j−arr[i]])mod(10^9+7)"

Company Tags

Nutanix Target HashiCorp Alibaba Epic Games GE Healthcare Robinhood Etsy OYO Rooms Instacart Ernst & Young Swiggy Deloitte Visa Oracle Byju's Lyft KPMG Riot Games Uber Zynga Seagate Technology Activision Blizzard Databricks Chewy Google Microsoft Amazon Meta Apple Netflix Adobe