Like Kadane’s algo. This question can be solved with a similar technique. The main observation to solve this problem is that at every index you either continue the longest bitwise AND subarray or you start a new one. Why?? Because of the way AND works once you remove a bit from a subarray bitwise AND then you can’t set it back effectively making all the next subarray containing that item smaller than they could be without it. Now after every iteration you can compare the answer so far with the current answer and return that.

class Solution {
public:
int longestSubarray(vector<int>& nums) {
unsigned int bwAnd = nums[0];
int len = 1, ans = 1;
unsigned int maximBWAND = bwAnd;

for(int i = 1;i < nums.size(); i++){
unsigned int casted = nums[i];
unsigned int temp = bwAnd & casted;
if(temp >= bwAnd && temp >= casted ){
len++;
bwAnd = temp;
}else{
len = 1;
bwAnd = casted;
}

if(bwAnd > maximBWAND){
ans = 1;
maximBWAND = bwAnd;
}else if(bwAnd == maximBWAND){
ans = max(len, ans);
}
}

return ans;
}
};

--

--

carlosbf
carlosbf

Written by carlosbf

Software developer that publishes his interview prep and leetcode hobby on this blog

No responses yet