LeetCode 题解工作台
按位与最大的最长子数组
给你一个长度为 n 的整数数组 nums 。 考虑 nums 中进行 按位与(bitwise AND) 运算得到的值 最大 的 非空 子数组。 换句话说,令 k 是 nums 任意 子数组执行按位与运算所能得到的最大值。那么,只需要考虑那些执行一次按位与运算后等于 k 的子数组。 返回满足要求的 最…
3
题型
9
代码语言
3
相关题
当前训练重点
中等 · 数组·结合·位运算·操作
答案摘要
由于按位与的操作,不会使得数字变大,因此最大值就是数组中的最大值。 题目可以转换为求最大值在数组中最多连续出现的次数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·位运算·操作 题型思路
题目描述
给你一个长度为 n 的整数数组 nums 。
考虑 nums 中进行 按位与(bitwise AND)运算得到的值 最大 的 非空 子数组。
- 换句话说,令
k是nums任意 子数组执行按位与运算所能得到的最大值。那么,只需要考虑那些执行一次按位与运算后等于k的子数组。
返回满足要求的 最长 子数组的长度。
数组的按位与就是对数组中的所有数字进行按位与运算。
子数组 是数组中的一个连续元素序列。
示例 1:
输入:nums = [1,2,3,3,2,2] 输出:2 解释: 子数组按位与运算的最大值是 3 。 能得到此结果的最长子数组是 [3,3],所以返回 2 。
示例 2:
输入:nums = [1,2,3,4] 输出:1 解释: 子数组按位与运算的最大值是 4 。 能得到此结果的最长子数组是 [4],所以返回 1 。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 106
解题思路
方法一:脑筋急转弯
由于按位与的操作,不会使得数字变大,因此最大值就是数组中的最大值。
题目可以转换为求最大值在数组中最多连续出现的次数。
我们先遍历数组 找到最大值 ,然后再遍历数组一次,找到最大值连续出现的次数,最后返回这个次数即可。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
mx = max(nums)
ans = cnt = 0
for x in nums:
if x == mx:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) for a single pass to find maximum and scan subarrays. Space complexity is O(1) since only counters are maintained, no extra structures. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Expect recognition that bitwise AND is maximized by the largest single number.
- question_mark
Look for O(N) single-pass solutions avoiding nested loops.
- question_mark
Check if candidate counts consecutive maximum elements correctly.
常见陷阱
外企场景- error
Confusing bitwise AND logic and trying to AND all subarrays explicitly.
- error
Using extra arrays or sets, which increases space unnecessarily.
- error
Failing to reset the consecutive count when a smaller element appears.
进阶变体
外企场景- arrow_right_alt
Find longest subarray with minimum bitwise OR instead of AND.
- arrow_right_alt
Determine the longest subarray where all elements are equal to a given target.
- arrow_right_alt
Count the number of subarrays achieving the maximum bitwise AND instead of the longest length.