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.
1#include <vector>
2#include <algorithm>
3#include <iostream>
4
5class Solution {
6public:
7 int countMaxOrSubsets(std::vector<int>& nums) {
8 int maxOr = 0, count = 0;
9 int numsSize = nums.size();
10 int totalSubsets = 1 << numsSize;
11 for (int mask = 0; mask < totalSubsets; ++mask) {
12 int orValue = 0;
13 for (int i = 0; i < numsSize; ++i) {
14 if (mask & (1 << i)) {
15 orValue |= nums[i];
16 }
17 }
18 if (orValue > maxOr) {
19 maxOr = orValue;
20 count = 1;
21 } else if (orValue == maxOr) {
22 count++;
23 }
24 }
25 return count;
26 }
27};
28
29int main() {
30 Solution sol;
31 std::vector<int> nums = {3, 2, 1, 5};
32 std::cout << "Output: " << sol.countMaxOrSubsets(nums) << std::endl;
33 return 0;
34}
The C++ solution iterates over all possible combinations (subsets) generated using a bitmask representation. For each subset, we compute its bitwise OR and compare this with the current maximum OR as we proceed. This method ensures that we do not miss any possible combinations.
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.
1#include <iostream>
2#include <vector>
3
4class Solution {
5public:
6 int countMaxOrSubsets(std::vector<int>& nums) {
7 int maxOr = 0, count = 0;
8 int numsSize = nums.size();
9 int totalSubsets = 1 << numsSize;
10 for (int mask = 1; mask < totalSubsets; ++mask) {
11 int orValue = 0;
12 for (int i = 0; i < numsSize; ++i) {
13 if (mask & (1 << i)) {
14 orValue |= nums[i];
15 }
16 }
17 if (orValue > maxOr) {
18 maxOr = orValue;
19 count = 1;
20 } else if (orValue == maxOr) {
21 count++;
22 }
23 }
24 return count;
25 }
26};
27
28int main() {
29 Solution sol;
30 std::vector<int> nums = {3, 2, 1, 5};
31 std::cout << "Output: " << sol.countMaxOrSubsets(nums) << std::endl;
32 return 0;
33}
The C++ implementation uses bit masking to enumerate all possible subsets for calculation of subset ORs. It then updates the global maximum OR and count of such subsets to derive the result.