Longest Subarray With Maximum Bitwise AND

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 \leq nums.length \leq {10}^{5}$
$1 \leq nums[i] \leq {10}^{6}$

 

解题思路

  比赛的时候还真没想出来怎么做,过了很久才想出来做法,主要是忽略了按位与得到的结果不会变大这个性质。

  $a \& b$一定满足$a \& b \leq a$并且$a \& b \leq b$。考虑每一位,如果按位与的两位都是$1$,那么得到的结果是$1$;如果按位与的两位存在一位是$0$,那么得到的结果是$0$。因此可以发现对于每一位,当进行一次与运算后结果不会变大只有可能变小。

  因此取单个数一定可以得到最大值。先枚举出整个数组的最大值,因为越与越小,因此如果想要结果是这个最大值,那么这个区间的每一个数都要是这个最大值才可以。因此问题就变成了找到一个长度最长的区间,且区间中所有值都是最大值。

  AC代码如下:

 1 class Solution {
 2 public:
 3     int longestSubarray(vector<int>& nums) {
 4         int maxv = *max_element(nums.begin(), nums.end());
 5         int ret = 0;
 6         for (int i = 0; i < nums.size(); i++) {
 7             int t = i;
 8             while (t < nums.size() && nums[t] == maxv) {
 9                 t++;
10             }
11             ret = max(ret, t - i);
12             i = t;
13         }
14         return ret;
15     }
16 };

 

参考资料

  力扣第312场周赛:https://www.bilibili.com/video/BV13Y4y1K7eU

posted @ 2022-09-25 16:07  onlyblues  阅读(39)  评论(0编辑  收藏  举报
Web Analytics