Similar Problems
Similar Problems not available
The Number Of Good Subsets - Leetcode Solution
Companies:
LeetCode: The Number Of Good Subsets Leetcode Solution
Difficulty: Hard
Topics: math dynamic-programming bit-manipulation array
Problem Statement:
You are given an integer array nums. We call a subset of nums good if its sum is greater than or equal to k.
Return the number of good subsets of nums.
A subset of an array is a group of zero or more selected elements.
Constraints:
1 <= nums.length <= 30 1 <= nums[i] <= 10^5 1 <= k <= 10^9
Example Input:
nums = [2,2,4,3], k = 6
Example Output:
5
Explanation:
The good subsets are [2], [2], [4], [2,2], [2,4]. Their respective sums are 2, 2, 4, 4, 6, all of which are greater than or equal to 6.
Solution:
This problem can be solved using dynamic programming. We will use a one-dimensional array, dp, to keep track of the number of good subsets that can be formed if we add each element of nums to the subset. We will iterate through nums from the beginning, updating dp as we go along.
dp[i] will represent the number of good subsets that can be formed using elements from nums[0] to nums[i]. For each i, we will iterate through all the j indices before i, adding dp[j] to dp[i] if the sum of the elements from nums[j+1] to nums[i] is greater than or equal to k.
At the end, we will have the total number of good subsets in dp[nums.length-1].
Here's the code:
class Solution { public int numOfSubarrays(int[] nums, int k) { int[] dp = new int[nums.length]; int count = 0; if(nums[0] >= k) { dp[0] = 1; count++; } for(int i = 1; i < nums.length; i++) { if(nums[i] >= k) { dp[i] = dp[i-1] + 1; count += dp[i]; } else { for(int j = i-1; j >= 0; j--) { if(nums[i] + nums[j] >= k) { dp[i] += dp[j]; count += dp[j]; } } } } return count; } }
Time Complexity:
The time complexity of this solution is O(n^2) because we iterate through all the j indices before i.
Space Complexity:
The space complexity of this solution is O(n) because we use a one-dimensional array dp to keep track of the number of good subsets.
The Number Of Good Subsets Solution Code
1