1493. Longest Subarray of 1's After Deleting One Element #2090
-
Topics: Given a binary array Return the size of the longest non-empty subarray containing only Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the longest contiguous subarray of 1's after deleting exactly one element from the given binary array. The solution involves using a sliding window technique to maintain a window that contains at most one zero. The key insight is that by allowing at most one zero in the window, we can simulate the deletion of that zero to obtain a contiguous segment of 1's. The length of this segment will be the window length minus one, accounting for the deleted element. Approach
Let's implement this solution in PHP: 1493. Longest Subarray of 1's After Deleting One Element <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function longestSubarray($nums) {
$left = 0;
$zeros = 0;
$max_len = 0;
$n = count($nums);
for ($right = 0; $right < $n; $right++) {
if ($nums[$right] == 0) {
$zeros++;
}
while ($zeros > 1) {
if ($nums[$left] == 0) {
$zeros--;
}
$left++;
}
$max_len = max($max_len, $right - $left);
}
return $max_len;
}
// Test cases
echo longestSubarray([1,1,0,1]) . "\n"; // 3
echo longestSubarray([0,1,1,1,0,1,1,0,1]) . "\n"; // 5
echo longestSubarray([1,1,1]) . "\n"; // 2
?> Explanation:
This approach efficiently processes the array in linear time, making it optimal for large inputs. The sliding window ensures that we only traverse each element once, maintaining an O(n) time complexity. The space complexity is O(1) as we use only a few variables. |
Beta Was this translation helpful? Give feedback.
We need to find the longest contiguous subarray of 1's after deleting exactly one element from the given binary array. The solution involves using a sliding window technique to maintain a window that contains at most one zero. The key insight is that by allowing at most one zero in the window, we can simulate the deletion of that zero to obtain a contiguous segment of 1's. The length of this segment will be the window length minus one, accounting for the deleted element.
Approach
left
andright
. Theright
pointer expands the window by moving forward, while theleft
pointer contracts the window if the number of zeros …