From 5c74fda2c5821381227075565c1ddbdc20e36a06 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Wed, 6 Nov 2024 21:23:34 -0700 Subject: 2275. largest combination with bitwise and greater than zero --- largest_and_greater_zero.c | 26 ++++++++++++++++++++++++++ largest_and_greater_zero.py | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 largest_and_greater_zero.c create mode 100644 largest_and_greater_zero.py diff --git a/largest_and_greater_zero.c b/largest_and_greater_zero.c new file mode 100644 index 0000000..2e28f2a --- /dev/null +++ b/largest_and_greater_zero.c @@ -0,0 +1,26 @@ +// 2275. Largest Combination With Bitwise AND Greater Than Zero +#include "leetcode.h" + +/* + * the bitwise and of an array 'nums' is the bitwise nd of all integers in + * 'nums'. 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 zero. + */ + +int largestCombination(int *candidates, int candidatesSize) { + int ans = 0, curr; + for (int i = 0; i < 30; ++i, curr = 0) + for (int j = 0; j < candidatesSize; ++j) { + curr += (candidates[j] >> i) & 1; + ans = fmax(ans, curr); + } + return ans; +} + +int main() { + int c1[] = {16, 17, 71, 62, 12, 24, 14}, c2[] = {8, 8}; + printf("%d\n", largestCombination(c1, ARRAY_SIZE(c1))); // expect: 4 + printf("%d\n", largestCombination(c2, ARRAY_SIZE(c2))); // expect: 2 +} diff --git a/largest_and_greater_zero.py b/largest_and_greater_zero.py new file mode 100644 index 0000000..c5964d6 --- /dev/null +++ b/largest_and_greater_zero.py @@ -0,0 +1,24 @@ +# 2275. Largest Combination With Bitwise AND Greater Than Zero + +""" +the bitwise and of an array 'nums' is the bitwise nd of all integers in +'nums'. 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 zero. +""" + + +class Solution(object): + def largestCombination(self, candidates): + """ + :type candidates: List[int] + :rtype: int + """ + return max(sum(1 << i & j > 0 for j in candidates) for i in range(30)) + + +if __name__ == "__main__": + obj = Solution() + print(obj.largestCombination(candidates=[16, 17, 71, 62, 12, 24, 14])) + print(obj.largestCombination(candidates=[8, 8])) -- cgit v1.2.3