DEV Community

Sachin Yadav
Sachin Yadav

Posted on

Leetcode 1493 Longest Subarray of 1's After Deleting One Element

This problem is based on the sliding window technique.

Trick To Solve :- Instead of looking at this problem like deleting one element, this problem can actually be viewed as solving the longest subarray of 1 having at most one zero.

Solve using the at most one zero approach and then return maxLen-1 and not maxLen because you have solved for at most one zero.

One benefit of solving this problem is that, The exact same to same code can be used for another leetcode problem named Max Consecutive Ones III.

Please note in Max Consecutive Ones III we don't return maxLen-1 rather we return maxLen.

/**
 * @param {number[]} nums
 * @return {number}
 */
var longestSubarray = function (nums) {
    let i = 0
    let j = 0
    let n = nums.length
    let maxLen = 0
    let zeroCount = 0
    while (j < n) {
        let num = nums[j]
        if (num == 0) {
            zeroCount++
        }
        while (zeroCount > 1) {
            if (nums[i] == 0) {
                zeroCount--
            }
            i++
        }
        maxLen = Math.max(maxLen, j - i + 1)
        j++
    }
    return maxLen - 1
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)