2275. Largest Combination With Bitwise AND Greater Than Zero Medium

@problem@discussion
#Array#Hash Table#Bit Manipulation#Counting



1/**
2 * [2275] Largest Combination With Bitwise AND Greater Than Zero
3 *
4 * The bitwise AND of an array nums is the bitwise AND of all integers in nums.
5 *
6 * For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
7 * Also, for nums = [7], the bitwise AND is 7.
8 *
9 * You are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination.
10 * Return the size of the largest combination of candidates with a bitwise AND greater than 0.
11 *  
12 * Example 1:
13 *
14 * Input: candidates = [16,17,71,62,12,24,14]
15 * Output: 4
16 * Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.
17 * The size of the combination is 4.
18 * It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.
19 * Note that more than one combination may have the largest size.
20 * For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.
21 *
22 * Example 2:
23 *
24 * Input: candidates = [8,8]
25 * Output: 2
26 * Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.
27 * The size of the combination is 2, so we return 2.
28 *
29 *  
30 * Constraints:
31 *
32 * 1 <= candidates.length <= 10^5
33 * 1 <= candidates[i] <= 10^7
34 *
35 */
36pub struct Solution {}
37
38// problem: https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/
39// discuss: https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/discuss/?currentPage=1&orderBy=most_votes&query=
40
41// submission codes start here
42
43impl Solution {
44    pub fn largest_combination(candidates: Vec<i32>) -> i32 {
45        let mut max = 0;
46        for i in 0..32 {
47            let mut current = 0;
48            for c in &candidates {
49                current += if c & (1 << i) > 0 { 1 } else { 0 }
50            }
51            if current > max {
52                max = current
53            }
54        }
55        max
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_2275_1() {
67        assert_eq!(
68            Solution::largest_combination(vec![16, 17, 71, 62, 12, 24, 14]),
69            4
70        );
71        assert_eq!(
72            Solution::largest_combination(vec![8, 8]),
73            2
74        );
75    }
76}
77


Back
© 2025 bowen.ge All Rights Reserved.