Longest Subarray of 1's After Deleting One Element LeetCode solution in JavaScript

1
var longestSubarray = function (nums) {
2
let l = 0,
3
r = 0;
4
let longest = 0;
5
// Keep track of the idx where the last zero was seen
6
let zeroIdx = null;
7
while (r < nums.length) {
8
// If we encounter a zero
9
if (nums[r] === 0) {
10
// If this is the first zero encountered, then set the zeroIdx to the current r index
11
if (zeroIdx === null) zeroIdx = r;
12
else {
13
// If we've already encountered a zero, then set the l index to the zeroIdx + 1,
14
// effectively removing that zero from the subarray
15
l = zeroIdx + 1;
16
// Then update the zeroIdx to the current r index
17
// This way there will be, at most, one zero in the subarray at all times
18
zeroIdx = r;
19
}
20
}
21
longest = Math.max(longest, r - l);
22
r++;
23
}
24
return longest;
25
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0