I am looking at solutions for LeetCode problem 1493. Longest Subarray of 1's After Deleting One Element:
Given a binary array
nums
, you should delete one element from it.Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.
Example 1
Input:
nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2,[1,1,1]
contains 3 numbers with value of 1's.Example 2
Input:
nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4,[0,1,1,1,1,1,0,1]
longest subarray with value of 1's is[1,1,1,1,1]
.Constraints:
1 <= nums.length <= 105
nums[i]
is either 0 or 1.
I found a super clean solution in the submission pool, which I believe to be beneficial if I can understand how it worked, but I just can't.
class Solution(object):
def longestSubarray(self, nums):
ans = 0
zero = 0
left = 0
for i, v in enumerate(nums):
if v == 0:
zero += 1
if zero > 1:
if nums[left] == 0:
zero -= 1
left += 1
return i - left
I think, from the return statement, it's clear that left
is used to count the zeros from left, and the un-counted 1.
I see how it tracks how many unused zeros on the left.
But how does it track the 1s that are not included?
And why this algorithm still works for when the longest subarray appears in the middle, as it continues further, passing beyond the longest subarray?
I guess I'm just confused here...