Largest Combination With Bitwise AND Greater Than Zero - Count Individual Bits [JS]

Description 

Solution: Count Individual Bits

To have a bitwise AND sum larger than 0, we only need one bit that hasn't been cancelled out.
Populate an array count, where count[i]indicates the number of candidates where the ith bit is 1.
Get the maximum count.

Time Complexity: O(n)
Space Complexity: O(1)

var largestCombination = function(candidates) {
  let count = Array(32).fill(0);
  for (let num of candidates) {
    let number = num, pos = 0;
    while (number > 0) {
      let bit = number & 1;
      if (bit) count[pos]++;
      number = number >> 1;
      pos++;
    }
  }
  return Math.max(...count);
};

javascript

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]