2044. Count Number of Maximum Bitwise-OR Subsets #719
-
Topics: Given an integer array An array The bitwise OR of an array Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can follow these steps:
Let's implement this solution in PHP: 2044. Count Number of Maximum Bitwise-OR Subsets <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function countMaxBitwiseORSubsets($nums) {
// Step 1: Calculate the maximum bitwise OR of the entire array
$maxOR = 0;
foreach ($nums as $num) {
$maxOR |= $num; // Bitwise OR operation
}
// Step 2: Initialize the count of valid subsets
$count = 0;
$n = count($nums);
// Step 3: Enumerate all subsets using bit manipulation
// There are 2^n subsets, we loop from 1 to (2^n) - 1 to skip the empty subset
for ($i = 1; $i < (1 << $n); $i++) {
$currentOR = 0;
for ($j = 0; $j < $n; $j++) {
// Check if the j-th bit is set in i
if ($i & (1 << $j)) {
$currentOR |= $nums[$j]; // Include this element in the subset
}
}
// Step 4: Check if the current subset's OR equals maxOR
if ($currentOR == $maxOR) {
$count++;
}
}
return $count;
}
// Example usage
$nums1 = [3, 1];
echo countMaxBitwiseORSubsets($nums1) . "\n"; // Output: 2
$nums2 = [2, 2, 2];
echo countMaxBitwiseORSubsets($nums2) . "\n"; // Output: 7
$nums3 = [3, 2, 1, 5];
echo countMaxBitwiseORSubsets($nums3) . "\n"; // Output: 6
?> Explanation:
This solution is efficient given the constraints and should work well for arrays of size up to 16, resulting in at most 65,535 subsets to evaluate. |
Beta Was this translation helpful? Give feedback.
We can follow these steps:
Calculate the Maximum Bitwise OR: The maximum bitwise OR of a subset can be determined by performing a bitwise OR operation across all elements of the array. This gives us the maximum possible bitwise OR.
Enumerate All Subsets: Since the size of the array is small (up to 16), we can enumerate all possible subsets using a bit manipulation technique. For an array of size
n
, there are2^n
possible subsets.Count Valid Subsets: For each subset, compute its bitwise OR and check if it matches the maximum bitwise OR. If it does, increment a counter.
Let's implement this solution in PHP: 2044. Count Number of Maximum Bitwise-OR Subsets