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.
1class Solution:
2 def countMaxOrSubsets(self, nums):
3 self.max_or = 0
4 self.count = 0
5
6 def dfs(index, current_or):
7 if index == len(nums):
8 if current_or > self.max_or:
9 self.max_or = current_or
10 self.count = 1
11 elif current_or == self.max_or:
12 self.count += 1
13 return
14 # Include nums[index]
15 dfs(index + 1, current_or | nums[index])
16 # Don't include nums[index]
17 dfs(index + 1, current_or)
18
19 dfs(0, 0)
20 return self.count
21
22solution = Solution()
23nums = [3, 2, 1, 5]
24print("Output:", solution.countMaxOrSubsets(nums))
In the Python solution, a dfs()
function is defined within the main function to recursively explore combinations. At the leaf of this recursion, we evaluate and update both the maximum OR and the count of subsets achieving it if applicable.
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.
JavaScript implementation demonstrates bit manipulation to derive OR outcomes while iterating; maximum OR value alignment with mask matching subset evaluations allows efficient determination of subset counts achieving it.