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 <= 105
nums[i]
is either 0
or 1
.
class Solution {
public:
int longestSubarray(vector& nums) {
// Initialize variables: midZero is the index of the previous zero, i and j are pointers, ans is the final answer
int midZero = -1; // Initialize to -1 as there is no previous zero initially
int i = 0; // Start pointer
int j = 0; // End pointer
int ans = 0; // Variable to store the final result
int n = nums.size(); // Size of the input array
// Iterate through the array using the end pointer (j)
while (j < n) {
// If the current element at the end pointer is 0
if (nums[j] == 0) {
// Update the answer with the length of the current subarray (excluding the 0)
ans = max(ans, j - i - 1);
// Move the start pointer (i) to the index after the previous zero (midZero + 1)
i = midZero + 1;
// Update midZero to the current index (j)
midZero = j;
}
// Move the end pointer to the next element
j++;
}
// Update the answer one last time after reaching the end of the array
ans = max(ans, j - i - 1);
// Return the final result
return ans;
}
};
In this program, the goal is to find the length of the longest subarray in the given vector ‘nums’ such that the subarray can be obtained by removing at most one zero. This solution includes a sliding window approach to efficiently explore the array.
Let’s see the step-by-step approach to the problem:
If it does, it updates the answer (‘ans’) by taking the maximum between the current answer and the length of length of the subarray from the previous zero (‘ j-i-1 ‘).
Summary:- This solution maintains a sliding window and considers the impact of removing at most one zero to maximise the length of the subarray. The time complexity is O( n ) , where n is the length of the input array.
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India