Count of Sub-Multisets With Bounded Sum - Problem
Imagine you're a data scientist working with a collection of non-negative integers. Your task is to find how many different ways you can select elements from this collection such that their sum falls within a specific range [l, r].
Here's the twist: you're working with a multiset, which means you can have duplicate values, but you can only use each occurrence once. For example, if you have [1, 2, 2, 3], you can use both 2's, but not three 2's.
What makes this challenging:
- A sub-multiset can contain 0 to all occurrences of each unique value
- Two sub-multisets are considered the same if they contain the same elements with the same frequencies
- The empty multiset has a sum of 0 and counts toward your answer if
l ≤ 0 ≤ r - Since the answer can be very large, return it modulo
10^9 + 7
Example: Given nums = [1, 2, 2], l = 1, r = 3
Possible sub-multisets and their sums: [] (0), [1] (1), [2] (2), [1,2] (3), [2,2] (4)
Sub-multisets with sum in [1,3]: [1], [2], [1,2] → Answer: 3
Input & Output
example_1.py — Basic Case
$
Input:
nums = [1, 2, 2], l = 1, r = 3
›
Output:
3
💡 Note:
Sub-multisets with sum in [1,3]: [1] (sum=1), [2] (sum=2), [1,2] (sum=3). Total count: 3.
example_2.py — With Zeros
$
Input:
nums = [0, 1, 2], l = 0, r = 2
›
Output:
6
💡 Note:
Sub-multisets: [] (0), [0] (0), [1] (1), [2] (2), [0,1] (1), [0,2] (2). All have sum in [0,2], so answer is 6.
example_3.py — Large Range
$
Input:
nums = [1, 2, 3], l = 0, r = 10
›
Output:
8
💡 Note:
All possible sub-multisets: [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]. All have sum ≤ 10, so answer is 8.
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- 0 ≤ nums[i] ≤ 2 × 104
- 0 ≤ l ≤ r ≤ 2 × 104
- All elements are non-negative integers
- Answer should be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Count Cookie Types
Group identical cookies: 1 chocolate chip (50 cal), 2 oatmeal (100 cal each)
2
DP Magic
Instead of trying all combinations, count them mathematically using dp[calories] = ways
3
Process Each Type
For each cookie type, update all possible calorie sums by adding that cookie
4
Sum Target Range
Add up dp[l] + dp[l+1] + ... + dp[r] for final answer
Key Takeaway
🎯 Key Insight: Instead of generating exponentially many combinations, use DP to count them mathematically. Handle duplicates by frequency, zeros separately, and sum the range [l,r] for the final answer.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code