LC2275. 按位与结果大于零的最长组合

题目链接:https://leetcode.cn/problems/largest-combination-with-bitwise-and-greater-than-zero/

题解

  • 标准贪心题目,按位与最后结果要大于 1,对应选择的数字在某一个二进制位上都是 1。所以反过来统计每一个二进制位上为 1 的数字有几个,取最大就是最后的答案。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def largestCombination(self, candidates: List[int]) -> int:

ans = 0
for i in range(32):
tmp = 0
now = 1 << i
# print(i, now)
for c in candidates:
if c & now > 0:
tmp += 1
ans = max(tmp, ans)
return ans

LC2275. 按位与结果大于零的最长组合

https://blog.xiang578.com/problem/lc2275.html

作者

Ryen Xiang

发布于

2025-01-12

更新于

2025-01-12

许可协议


网络回响

评论