Largest Combination With Bitwise AND Greater Than Zero

medium array hash map bit manipulation counting

Problem

Return the size of the largest subset whose AND is > 0. Equivalent to: the largest count of numbers that share a common set bit.

Inputcandidates = [16, 17, 71, 62, 12, 24, 14]
Output4
Bit 4 (16) is set in 4 of them: {16, 17, 24, 71}.

def largest_combination(candidates):
    best = 0
    for b in range(32):
        cnt = sum(1 for x in candidates if x >> b & 1)
        best = max(best, cnt)
    return best
function largestCombination(candidates) {
  let best = 0;
  for (let b = 0; b < 32; b++) {
    let cnt = 0;
    for (const x of candidates) if ((x >> b) & 1) cnt++;
    if (cnt > best) best = cnt;
  }
  return best;
}
class Solution {
    public int largestCombination(int[] candidates) {
        int best = 0;
        for (int b = 0; b < 32; b++) {
            int cnt = 0;
            for (int x : candidates) if (((x >> b) & 1) != 0) cnt++;
            best = Math.max(best, cnt);
        }
        return best;
    }
}
int largestCombination(vector<int>& candidates) {
    int best = 0;
    for (int b = 0; b < 32; b++) {
        int cnt = 0;
        for (int x : candidates) if ((x >> b) & 1) cnt++;
        best = max(best, cnt);
    }
    return best;
}
Time: O(32·n) Space: O(1)