ACM준비/LeetCode

2275. Largest Combination With Bitwise AND Greater Than Zero

조규현15 2024. 11. 8. 00:03
반응형

2275. Largest Combination With Bitwise AND Greater Than Zero
Solved
Medium
Topics
Companies
Hint
The bitwise AND of an array nums is the bitwise AND of all integers in nums.

For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.
Also, for nums = [7], the bitwise AND is 7.
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.

Return the size of the largest combination of candidates with a bitwise AND greater than 0.


접근

배열로 주어진 숫자들의 bit 를 모두 계산합니다.

2 진법 ( bits ) 으로 변경한 값은 And 연산으로 같은 위치 ( index ) 에 '1' 이 존재하면 결과 값으로 0 보다 큰 숫자로 반환됩니다.

And 연산은 한번만 이뤄지므로 후보군의 모든 숫자들의 index 별 1 의 갯수를 더하면 And 연산으로 이뤄질 수 있는 숫자들의 합이 됩니다.

위 예시에서는 3 번째 위치의 1 의 갯수가 '2' 이므로 '7' 과 '5' 의 And 가 가장 많은 숫자를 사용한 경우입니다.

답은 '2' 입니다.


코드

/**
 * @param {number[]} candidates
 * @return {number}
 */
var largestCombination = function (candidates) {
    var bits = {};

    for (var i = 0; i < candidates.length; i++) {
        var e = candidates[i];
        var j = 0;
        while (e > 0) {
            if (e % 2 == 1) {
                bits[j] = (bits[j] || 0) + 1;
            }
            e = e >> 1;
            j++;
        }
    }

    var r = Math.max(...Object.values(bits));
    return r;
};
반응형

'ACM준비 > LeetCode' 카테고리의 다른 글

1829. Maximum XOR for Each Query  (0) 2024.11.09
3011. Find if Array Can Be Sorted  (0) 2024.11.08
205. Isomorphic Strings  (1) 2024.04.03
2542. Maximum Subsequence Score  (0) 2023.05.25
703. Kth Largest Element in a Stream  (0) 2023.05.23