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.
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.
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.