LeetCode 2902: Count of Sub-Multisets With Bounded Sum

LeetCode 2902 Solution Explanation

Explanation

To solve this problem, we can use dynamic programming. We will iterate through each element in the input array nums and for each element, we will calculate the count of sub-multisets that fall within the range [l, r] considering that element. We will maintain a 2D array dp where dp[i][j] represents the count of sub-multisets whose sum is j considering the first i elements of the input array.

At each step, we will update the dp array based on the current element being considered. To calculate the count of sub-multisets for the current element, we will consider two cases: including the current element in the subset and excluding the current element from the subset.

Finally, we will sum up the counts for all possible sums within the range [l, r] to get the total count of valid sub-multisets.

Time Complexity: O(n * (r-l+1)) where n is the length of the input array nums and (r-l+1) is the range of sums.

Space Complexity: O(n * (r-l+1)) for the dp array.

LeetCode 2902 Solutions in Java, C++, Python

class Solution {
    public int countSubsets(int[] nums, int l, int r) {
        int mod = 1000000007;
        int n = nums.length;
        int[][] dp = new int[n + 1][r - l + 2];
        dp[0][0] = 1;

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j <= r - l + 1; j++) {
                dp[i][j] = (dp[i - 1][j] + dp[i - 1][j - nums[i - 1] + l]) % mod;
            }
        }

        int count = 0;
        for (int j = Math.max(0, l); j <= r; j++) {
            count = (count + dp[n][j - l]) % mod;
        }

        return count;
    }
}

Interactive Code Editor for LeetCode 2902

Improve Your LeetCode 2902 Solution

Use the editor below to refine the provided solution for LeetCode 2902. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems