Created
August 24, 2025 16:38
-
-
Save tatsuyax25/ae402953a852b1bd62c2beccd74eacd3 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finds the length of the longest subarray containing only 1s | |
* after deleting exactly one element (which can be a 0). | |
* | |
* @param {number[]} nums - Array of binary digits (0s and 1s) | |
* @return {number} - Length of the longest valid subarray | |
*/ | |
var longestSubarray = function(nums) { | |
let maxLength = 0; // Tracks the maximum length found | |
let left = 0; // Left pointer of the sliding window | |
let zeroCount = 0; // Number of zeros in the current window | |
for (let right = 0; right < nums.length; right++) { | |
// Expand the window by including nums[right] | |
if (nums[right] === 0) { | |
zeroCount++; | |
} | |
// Shrink the window if more than one zero is present | |
while (zeroCount > 1) { | |
if (nums[left] === 0) { | |
zeroCount--; | |
} | |
left++; // Move the left pointer forward | |
} | |
// Update maxLength (we subtract 1 to simulate deleting one element) | |
maxLength = Math.max(maxLength, right - left + 1); | |
} | |
// Subtract 1 to account for the required deletion | |
return maxLength - 1; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment