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.
The C solution iteratively calculates OR values for subsets encoded through bitmasks, iterating through possible subset representations and dynamically including elements based on bit positions, updating the maximum OR and associated subset count as it runs.