2419. Longest Subarray With Maximum Bitwise AND
Difficulty: Medium
Topics: Array, Bit Manipulation, Brainteaser
You are given an integer array nums of size n.
Consider a non-empty subarray from nums that has the maximum possible bitwise AND.
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:
Example 2:
Constraints:
Hint:
Solution:
Let's first break down the problem step by step:
Bitwise AND Properties:
Objective:
For the input array [1,2,3,3,2,2], the maximum value is 3. The longest contiguous subarray with only 3s is [3,3], which has a length of 2.
Let's implement this solution in PHP: 2419. Longest Subarray With Maximum Bitwise AND
Explanation:
- Step 1: We first find the maximum value in the array using PHP's built-in max() function.
- Step 2: We initialize two variables, $maxLength to store the length of the longest subarray and $currentLength to track the length of the current contiguous subarray of the maximum value.
- Step 3: We iterate through the array:
- If the current number equals the maximum value, we increment the length of the current subarray.
- If the current number does not equal the maximum value, we check if the current subarray is the longest so far and reset the length.
- Final Step: After the loop, we ensure that if the longest subarray is at the end of the array, we still consider it.
- Finally, we return the length of the longest subarray that contains only the maximum value.
Time Complexity:
For the input [1, 2, 3, 3, 2, 2], the output is 2, and for [1, 2, 3, 4], the output is 1, as expected.
This solution handles the constraints and efficiently solves the problem.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
以上是Longest Subarray With Maximum Bitwise AND的详细内容。更多信息请关注PHP中文网其他相关文章!