1493. Longest Subarray of 1's After Deleting One Element
Problem
Delete exactly one element from the binary array nums, then return the length of the longest non-empty subarray of only 1s (0 if there is none).
Example: [0,1,1,1,0,1,1,0,1] → 5; [1,1,1] → 2 (you must delete one)
Longest window containing at most one zero; the deleted element is inside it, so the answer is window length − 1 (which also handles the all-ones case, where a 1 must be deleted).
Complexity: O(n).
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
lo = zeros = best = 0
for hi, x in enumerate(nums):
zeros += x == 0
while zeros > 1:
zeros -= nums[lo] == 0
lo += 1
best = max(best, hi - lo) # (hi - lo + 1) - 1 deleted element
return best
assert Solution().longestSubarray([1, 1, 0, 1]) == 3
assert Solution().longestSubarray([0, 1, 1, 1, 0, 1, 1, 0, 1]) == 5
assert Solution().longestSubarray([1, 1, 1]) == 2
assert Solution().longestSubarray([0, 0, 0]) == 0
class Solution {
public int longestSubarray(int[] nums) {
int lo = 0, zeros = 0, best = 0;
for (int hi = 0; hi < nums.length; hi++) {
if (nums[hi] == 0) zeros++;
while (zeros > 1) if (nums[lo++] == 0) zeros--;
best = Math.max(best, hi - lo);
}
return best;
}
}
func longestSubarray(nums []int) int {
lo, zeros, best := 0, 0, 0
for hi, x := range nums {
if x == 0 {
zeros++
}
for zeros > 1 {
if nums[lo] == 0 {
zeros--
}
lo++
}
best = max(best, hi-lo) // (hi - lo + 1) - 1 deleted element
}
return best
}