
Sponsored
Sponsored
This approach involves finding the maximum element in the array since it would potentially be the maximum bitwise AND when considered individually or consecutively. Then, we scan through the array to find the longest subarray containing only this element.
Time Complexity: O(n) because we iterate through the array once.
Space Complexity: O(1) as no extra space is used apart from variables.
1function longestMaxAndSubarray(nums) {
2 let maxElement = 0;
3 let currentLength = 0;
4 let longestLength = 0;
5 for (let num of nums) {
6 if (num > maxElement) {
7 maxElement = num;
8 currentLength = 1;
9 longestLength = 1;
10 } else if (num === maxElement) {
11 currentLength++;
12 longestLength = Math.max(longestLength, currentLength);
13 } else {
14 currentLength = 0;
15 }
16 }
17 return longestLength;
18}
19
20const nums = [1, 2, 3, 3, 2, 2];
21console.log(longestMaxAndSubarray(nums));The implementation in JavaScript aligns with previous logic to assess the longest subarray of the most significant element in linear time.
This approach involves using a sliding window to determine the longest subarray where the bitwise AND remains at its maximum value. Begin from the end of the array since the maximum AND value after considering all elements is often the last element itself or a combination found traversing backward.
Time Complexity: O(n), as it involves a single backward traversal.
Space Complexity: O(1).
Initially, the maximum AND is assumed to be the last element. A reverse scan utilizing a sliding window calculates the longest subarray conforming to this value.