2044. Count Number of Maximum Bitwise-OR Subsets
MediumView on LeetCode
Time: O(2^n)
Space: O(n)
Problem Overview
Count Number of Maximum Bitwise-OR Subsets (Medium) asks you to solve a structured algorithmic task. This is a common Array / Bit Manipulation pattern in coding interviews. Compute max OR of whole array; DFS enumerate subsets counting those achieving max OR.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Compute max OR of whole array; DFS enumerate subsets counting those achieving max OR.
Related patterns: Array, Bit Manipulation, Backtracking
2044.cs
C#
// Approach: Compute max OR of whole array; DFS enumerate subsets counting those achieving max OR.
// Time: O(2^n) Space: O(n)
public class Solution
{
private int ans = 0;
public int CountMaxOrSubsets(int[] nums)
{
int ors = nums.Aggregate((a, b) => a | b);
Dfs(nums, 0, 0, ors);
return ans;
}
private void Dfs(int[] nums, int i, int path, int ors)
{
if (i == nums.Length)
{
if (path == ors)
++ans;
return;
}
Dfs(nums, i + 1, path, ors);
Dfs(nums, i + 1, path | nums[i], ors);
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 22. Generate Parentheses(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)