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

grid47
grid47
Exploring patterns and algorithms
Jun 10, 2024 6 min read

Given a binary array nums, you should delete one element from it. After deleting one element, return the size of the longest non-empty subarray containing only 1’s in the resulting array. If no such subarray exists, return 0.
Problem
Approach
Steps
Complexity
Input: You are given a binary array nums where each element is either 0 or 1.
Example: nums = [1, 0, 1, 1, 0]
Constraints:
• 1 <= nums.length <= 10^5
• nums[i] is either 0 or 1.
Output: Return the size of the longest contiguous subarray containing only 1's after deleting one element. If no such subarray exists, return 0.
Example: Output: 4
Constraints:
• The array will contain at least one element.
Goal: To maximize the length of contiguous 1's after deleting one element, we will use a sliding window approach to count the maximum subarray of 1's with at most one zero.
Steps:
• Initialize two pointers, `i` and `j`, for the sliding window.
• Count the zeros in the window and ensure there is at most one zero.
• If there is more than one zero, shrink the window from the left.
• Track the maximum length of the window that contains at most one zero.
Goal: The array has at least one element, and the number of elements can go up to 10^5.
Steps:
• 1 <= nums.length <= 10^5
• nums[i] is either 0 or 1.
Assumptions:
• The array nums contains only 0's and 1's.
• There will be at least one element in the array.
Input: nums = [1,0,1,1,0]
Explanation: After deleting the element at index 1, the array becomes [1, 1, 1, 0]. The longest subarray with only 1's is of length 4.

Input: nums = [0,1,1,0,1,1,1,0]
Explanation: After deleting the element at index 3, the array becomes [0, 1, 1, 1, 1, 1, 0]. The longest subarray of 1's is of length 5.

Input: nums = [1, 1, 1]
Explanation: After deleting one element, the remaining array has two 1's, so the longest subarray is of length 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus