Intermediate Level
Implement the longestSubarrayAfterDeletingOne method that returns the longest subarray of 1 values after deleting one element.
The input contains a binary array nums and its length size. Your task is to delete exactly one element from the array and then return the length of the longest continuous subarray containing only 1 values.
If the array already contains only ones, one element still has to be deleted.
For example, [1,1,0,1] becomes a run of length 3 after deleting the zero.
Use a sliding window that allows at most one zero inside it.
The zero inside the window represents the element that can be deleted. Therefore, the number of ones after deletion is windowLength - 1.
Whenever the window has more than one zero, move the left pointer until it becomes valid again. Track the maximum value of windowLength - 1.
Pseudocode:
function longestSubarrayAfterDeletingOne(nums, size):
left = 0
zeroCount = 0
best = 0
for right from 0 to size - 1:
if nums[right] == 0:
zeroCount++
while zeroCount > 1:
if nums[left] == 0:
zeroCount--
left++
best = maximum(best, right - left)
return best