LeetCode 3351: Sum of Good Subsequences Solution
Master LeetCode problem 3351 (Sum of Good Subsequences), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3351. Sum of Good Subsequences
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming with a bitmask approach. We create a dp array where dp[mask] represents the sum of all good subsequences that can be formed using elements whose binary representation corresponds to the mask. We start by initializing dp[1 << nums[i]] = 1 for each element in nums.
Then, for each mask, we iterate over all elements in nums and update the dp[mask] by adding dp[mask ^ (1 << nums[i])] if nums[i] - 1 or nums[i] + 1 exists in the mask.
Finally, we sum up all the values in the dp array to get the total sum of all good subsequences modulo 10^9 + 7.
Time Complexity: O(n * 2^n), where n is the number of elements in the input array nums. Space Complexity: O(2^n), where n is the number of elements in the input array nums.
Solution Code
class Solution {
public int sumOfGoodSubsequences(int[] nums) {
int MOD = 1000000007;
int n = nums.length;
long[] dp = new long[1 << 17];
Arrays.fill(dp, 0);
dp[0] = 1;
for (int num : nums) {
long[] next = Arrays.copyOf(dp, dp.length);
for (int i = 0; i < (1 << 17); i++) {
if (dp[i] == 0) continue;
int newMask = i | (1 << num);
next[newMask] += dp[i];
if (num > 0 && (i & (1 << (num - 1))) > 0) {
next[newMask] += dp[i];
}
next[newMask] %= MOD;
}
dp = next;
}
long ans = 0;
for (int i = 1; i < (1 << 17); i++) {
ans = (ans + dp[i]) % MOD;
}
return (int) ans;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3351 (Sum of Good Subsequences)?
This page provides optimized solutions for LeetCode problem 3351 (Sum of Good Subsequences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3351 (Sum of Good Subsequences)?
The time complexity for LeetCode 3351 (Sum of Good Subsequences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3351 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3351 in Java, C++, or Python.