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

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

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

Sum of Prefix Scores of Strings - Trie [JS]