[LeetCode] 2419. Longest Subarray With Maximum Bitwise AND

You are given an integer array nums of size n.

Consider a non-empty subarray from nums that has the maximum possible bitwise AND.

In other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.
Return the length of the longest such subarray.

The bitwise AND of an array is the bitwise AND of all the numbers in it.

A subarray is a contiguous sequence of elements within an array.

Example 1:
Input: nums = [1,2,3,3,2,2]
Output: 2
Explanation:
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.

Example 2:
Input: nums = [1,2,3,4]
Output: 1
Explanation:
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.

Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 106

按位与最大的最长子数组。

给你一个长度为 n 的整数数组 nums 。

考虑 nums 中进行 按位与(bitwise AND)运算得到的值 最大 的 非空 子数组。

换句话说,令 k 是 nums 任意 子数组执行按位与运算所能得到的最大值。那么,只需要考虑那些执行一次按位与运算后等于 k 的子数组。
返回满足要求的 最长 子数组的长度。

数组的按位与就是对数组中的所有数字进行按位与运算。

子数组 是数组中的一个连续元素序列。

思路

这道题考察的是对位运算的敏感度吧我觉得。注意 AND 运算有一个特点,假如你有一个足够大的数字,比如 15 好了,他的二进制表达是 1111(四个 1)。如果 15 是数组里最大的数字,那么他跟任何其他数字做 AND 操作的结果都只会让结果变得更小,因为其他比 15 小的数字的二进制表达里面包含 0,与 15 AND 之后,结果只会比 15 更小。

所以这道题我们找到数组最大值 max 之后,需要判断连续的 max 到底有几个。最后返回最长的子数组的长度。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int longestSubarray(int[] nums) {
int max = 0, res = 0, cnt = 0;
// First pass: find the maximum element
for (int num : nums) {
max = Math.max(max, num);
}

// Second pass: count the longest subarray of max elements
for (int num : nums) {
if (num == max) {
cnt++;
res = Math.max(res, cnt);
} else {
cnt = 0; // reset count when encountering a different element
}
}
return res;
}
}


[LeetCode] 2419. Longest Subarray With Maximum Bitwise AND
https://shurui91.github.io/posts/463918335.html
Author
Aaron Liu
Posted on
September 14, 2024
Licensed under