Sponsored
Sponsored
This approach involves generating all subsets using a bitmask. For each possible subset generated by the bitmask, compute the bitwise OR, and keep track of the maximum bitwise OR found. After calculating the OR for all subsets, we count how many subsets achieved the maximum OR value.
Time Complexity: O(n * 2^n), where n is the length of the array. There are 2^n possible subsets and computing the OR for each subset can take O(n) in the worst case.
Space Complexity: O(n) due to recursive call stack depth.
1function countMaxOrSubsets(nums) {
2 let maxOr = 0;
3 let count = 0;
4
5 function dfs(index, currentOr) {
6 if (index === nums.length) {
7 if (currentOr > maxOr) {
8 maxOr = currentOr;
9 count = 1;
10 } else if (currentOr === maxOr) {
11 count++;
12 }
13 return;
14 }
15 dfs(index + 1, currentOr | nums[index]);
16 dfs(index + 1, currentOr);
17 }
18
19 dfs(0, 0);
20 return count;
21}
22
23let nums = [3, 2, 1, 5];
24console.log("Output:", countMaxOrSubsets(nums));
This JavaScript solution implements a DFS strategy to explore subsets and calculate their OR values using similar logic. We maintain and update maxOr
tracking logic all through the recursive traversal of subset possibilities.
This approach employs an iterative method utilizing bitmasks to evaluate all potential subsets. For each possible subset marked by a bitmask, the bitwise OR is computed and retained if it represents a new maximum. The process counts how many subsets reach this maximal OR value, iterating over binary number representations to dynamically include or exclude each number in the subset.
Time Complexity: O(n * 2^n) - By iterating through all 2^n subsets and calculating ORs, computation scales linearly with each set size.
Space Complexity: O(1), since only fixed local variables manage computations.
public class Solution {
public int CountMaxOrSubsets(int[] nums) {
int maxOr = 0;
int count = 0;
int n = nums.Length;
int totalSubsets = 1 << n;
for (int mask = 1; mask < totalSubsets; ++mask) {
int orValue = 0;
for (int i = 0; i < n; ++i) {
if ((mask & (1 << i)) != 0) {
orValue |= nums[i];
}
}
if (orValue > maxOr) {
maxOr = orValue;
count = 1;
} else if (orValue == maxOr) {
count++;
}
}
return count;
}
public static void Main(string[] args) {
Solution sol = new Solution();
int[] nums = {3, 2, 1, 5};
Console.WriteLine("Output: " + sol.CountMaxOrSubsets(nums));
}
}
Within this C# solution, mask
operations allow subset identification along numeric combinations. As each subset OR is computed, it's measured against the maximum OR, and their count tallied efficiently.