LeetCode 1493: Longest Subarray of 1's After Deleting One Element Solution
Master LeetCode problem 1493 (Longest Subarray of 1's After Deleting One Element), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1493. Longest Subarray of 1's After Deleting One Element
Problem Explanation
Explanation
To solve this problem, we can iterate through the binary array and keep track of the lengths of consecutive sequences of 1's. When we encounter a single 0, we can calculate the length of the combined sequence if we were to remove that 0. We need to handle different cases of 0's occurring at the start, end, or in the middle of the array. The maximum length we find throughout the iteration will be our answer.
Algorithm
- Initialize variables:
countOnesto count consecutive 1's,prevCountto store the previous count,currCountfor the current count, andmaxLento store the maximum length found. - Iterate through the binary array:
- If the current element is 1, increment
currCount. - If the current element is 0:
- Update
maxLenwith the maximum ofmaxLen,prevCount + currCount, andcurrCount. - Update
prevCountwithcurrCount. - Reset
currCountto 0.
- Update
- If the current element is 1, increment
- Update
maxLenwith the maximum ofmaxLen,prevCount + currCount, andcurrCount. - Return
maxLen.
Time Complexity
The time complexity of this algorithm is O(n) where n is the length of the input array nums.
Space Complexity
The space complexity is O(1) as we are using a constant amount of extra space.
Solution Code
class Solution {
public int longestSubarray(int[] nums) {
int countOnes = 0;
int prevCount = 0;
int currCount = 0;
int maxLen = 0;
for (int num : nums) {
if (num == 1) {
currCount++;
} else {
maxLen = Math.max(maxLen, prevCount + currCount);
prevCount = currCount;
currCount = 0;
}
}
maxLen = Math.max(maxLen, prevCount + currCount);
return maxLen == nums.length ? maxLen - 1 : maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1493 (Longest Subarray of 1's After Deleting One Element)?
This page provides optimized solutions for LeetCode problem 1493 (Longest Subarray of 1's After Deleting One Element) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1493 (Longest Subarray of 1's After Deleting One Element)?
The time complexity for LeetCode 1493 (Longest Subarray of 1's After Deleting One Element) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1493 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1493 in Java, C++, or Python.