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].
Example 3:
Input: nums = [1,1,1] Output: 2 Explanation: You must delete one element.
Constraints:
1 <= nums.length <= 105nums[i] is either 0 or 1.This approach uses a sliding window technique with variables to keep track of the count of consecutive 1's before and after a zero. The main idea is to iterate through the array, and whenever you encounter more than one zero, calculate the length of 1's that can be formed by deleting the previous zero, update maximum length as needed, and reset counts.
The C solution iterates through the array and calculates the length of subarrays of 1's using counters. It uses variables to keep track of the length before and after a zero, and updates the maximum length as needed. Edge cases are handled by checking if the current maximum length equals the size of the array, indicating every element is 1 and one must be deleted.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), as we iterate through the array once.
Space Complexity: O(1), as no additional space is used proportional to input size.
This approach utilizes prefix sums to keep a cumulative count of 1's encountered and calculates lengths avoiding excessive recalculations. Two arrays store the prefix sum of 1's up to the current element and from the current element to the end, respectively. A single pass is then made to compute the maximum length by checking possible deletions at each zero.
This C solution efficiently constructs a prefix and suffix table with cumulative counts of consecutive 1's. With these, every possible 0 is evaluated by checking adjacent blocks, optimizing overall calculations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), each element is processed three independent times.
Space Complexity: O(n), proportional to input due to prefix and suffix arrays.
| Approach | Complexity |
|---|---|
| Sliding Window with Variables | Time Complexity: O(n), as we iterate through the array once. |
| Prefix Sum and Single Pass | Time Complexity: O(n), each element is processed three independent times. |
Longest Subarray of 1's After Deleting One Element | Multiple Approaches | GOOGLE | Leetcode-1493 • codestorywithMIK • 10,197 views views
Watch 9 more video solutions →Practice Longest Subarray of 1's After Deleting One Element with our built-in code editor and test cases.
Practice on FleetCode