2419. Longest Subarray With Maximum Bitwise AND #538
-
Topics: You are given an integer array 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:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Let's first break down the problem step by step: Key Insights:
Plan:
Example:For the input array Let's implement this solution in PHP: 2419. Longest Subarray With Maximum Bitwise AND <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function longestSubarray($nums) {
// Step 1: Find the maximum value in the array
$maxValue = max($nums);
// Step 2: Initialize variables to keep track of the longest subarray length
$maxLength = 0;
$currentLength = 0;
// Step 3: Traverse through the array to find the longest subarray with the max value
foreach ($nums as $num) {
if ($num == $maxValue) {
// Increment the current subarray length if it's equal to the max value
$currentLength++;
} else {
// Update the maxLength if the current sequence ends
if ($currentLength > $maxLength) {
$maxLength = $currentLength;
}
// Reset the current length since we encountered a different number
$currentLength = 0;
}
}
// Final check at the end in case the longest subarray is at the end of the array
if ($currentLength > $maxLength) {
$maxLength = $currentLength;
}
// Return the longest length found
return $maxLength;
}
// Test cases
$nums1 = [1, 2, 3, 3, 2, 2];
$nums2 = [1, 2, 3, 4];
echo "Output for [1, 2, 3, 3, 2, 2]: " . longestSubarray($nums1) . "\n"; // Output: 2
echo "Output for [1, 2, 3, 4]: " . longestSubarray($nums2) . "\n"; // Output: 1
?> Explanation:
Time Complexity:
Test Cases:For the input This solution handles the constraints and efficiently solves the problem. |
Beta Was this translation helpful? Give feedback.
Let's first break down the problem step by step:
Key Insights:
Bitwise AND Properties:
Objective:
Plan: