Count of Sub-Multisets With Bounded Sum Problem
Description
LeetCode Problem 2902.
You are given a 0-indexed array nums of non-negative integers, and two integers l and r.
Return the count of sub-multisets within nums where the sum of elements in each subset falls within the inclusive range of [l, r].
Since the answer may be large, return it modulo 10^9+ 7.
A sub-multiset is an unordered collection of elements of the array in which a given value x can occur 0, 1, ..., occ[x] times, where occ[x] is the number of occurrences of x in the array.
Note that:
- Two sub-multisets are the same if sorting both sub-multisets results in identical multisets.
- The sum of an empty multiset is
0.
Example 1:
Input: nums = [1,2,2,3], l = 6, r = 6
Output: 1
Explanation: The only subset of nums that has a sum of 6 is {1, 2, 3}.
Example 2:
Input: nums = [2,1,4,2,7], l = 1, r = 5
Output: 7
Explanation: The subsets of nums that have a sum within the range [1, 5] are {1}, {2}, {4}, {2, 2}, {1, 2}, {1, 4}, and {1, 2, 2}.
Example 3:
Input: nums = [1,2,1,3,5,2], l = 3, r = 5
Output: 9
Explanation: The subsets of nums that have a sum within the range [3, 5] are {3}, {5}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {1, 1, 2}, {1, 1, 3}, and {1, 2, 2}.
Constraints:
1 <= nums.length <= 2 * 10^40 <= nums[i] <= 2 * 10^4- Sum of
numsdoes not exceed2 * 10^4. 0 <= l <= r <= 2 * 10^4
Solution
Approach: Bounded Knapsack with Sliding Sums
Count sub-multisets by sum with memo[i] = number of sub-multisets with sum i. Zeros do not change any sum, so they only multiply the answer by cnt[0] + 1 at the end. The ones can be handled directly: memo[0..cnt[1]] are all 1.
For each other value n that occurs cnt[n] times, add the choices of 0..cnt[n] copies. Adding unlimited copies is a prefix-style update memo[i] += memo[i - n] for increasing i. That allows too many copies, so then remove the ones that used more than cnt[n] copies: for i going down from the current maximum sum to (cnt[n] + 1) * n, subtract memo[i - (cnt[n] + 1) * n]. Only sums up to r matter, and the running total of all values bounds the loops.
The answer is the sum of memo[l..r], times cnt[0] + 1, modulo 10^9 + 7. Since the values sum to at most 2 * 10^4, there are only about sqrt(2 * 10^4) distinct values, so the loops are cheap.
Complexity: time O(r sqrt(S)), space O(r), where S is the sum of the array.
import collections
class Solution:
def countSubMultisets(self, nums: List[int], l: int, r: int) -> int:
kMod = 1_000_000_007
# dp[i] := # of submultisets of nums with sum i
dp = [1] + [0] * r
count = collections.Counter(nums)
zeros = count.pop(0, 0)
for num, freq in count.items():
# stride[i] := dp[i] + dp[i - num] + dp[i - 2 * num] + ...
stride = dp.copy()
for i in range(num, r + 1):
stride[i] += stride[i - num]
for i in range(r, 0, -1):
if i >= num * (freq + 1):
# dp[i] + dp[i - num] + dp[i - freq * num]
dp[i] = stride[i] - stride[i - num * (freq + 1)]
else:
dp[i] = stride[i]
return (zeros + 1) * sum(dp[l : r + 1]) % kMod