2275. Largest Combination With Bitwise AND Greater Than Zero
MediumView on LeetCode
Time: O(n * 24)
Space: O(1)
Problem Overview
Count values that have all required bits set (value & bits == bits).
Intuition
Count values that have all required bits set (value & bits == bits). For each candidate in votes, check bitmask.
Algorithm
- 1For each candidate: if (candidate & bits) == bits: count++.
Common Pitfalls
- •All bits in the required mask must be set. Use bitwise AND.
2275.cs
C#
// Approach: For each bit position count how many candidates have that bit set; return max count.
// Time: O(n * 24) Space: O(1)
public class Solution
{
public int LargestCombination(int[] candidates)
{
const int kMaxBit = 24;
int ans = 0;
for (int i = 0; i < kMaxBit; ++i)
{
int count = 0;
foreach (var candidate in candidates)
{
if ((candidate >> i & 1) == 1)
++count;
}
ans = Math.Max(ans, count);
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)