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.
1using System;
2
3public class Solution {
4 private int maxOr = 0;
5 private int count = 0;
6
7 public int CountMaxOrSubsets(int[] nums) {
8 maxOr = 0;
9 count = 0;
10 FindSubsets(nums, 0, 0);
11 return count;
12 }
13
14 private void FindSubsets(int[] nums, int index, int currentOr) {
15 if (index == nums.Length) {
16 if (currentOr > maxOr) {
17 maxOr = currentOr;
18 count = 1;
19 } else if (currentOr == maxOr) {
20 count++;
21 }
22 return;
23 }
24 FindSubsets(nums, index + 1, currentOr | nums[index]);
25 FindSubsets(nums, index + 1, currentOr);
26 }
27
28 public static void Main(string[] args) {
29 Solution solution = new Solution();
30 int[] nums = {3, 2, 1, 5};
31 Console.WriteLine("Output: " + solution.CountMaxOrSubsets(nums));
32 }
33}
The C# solution uses FindSubsets()
function implemented in a similar manner as the other languages, recursively making a choice whether or not to include each element, updating our result with both maximum bitwise OR value and count of occurrences.
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.
This Java solution processes subsets through a masking technique, iterating over all possible binary representations to derive subset OR values and maintain maximum state through iterative handling and comparison.