Give simple, common, and optimised Java solution class Solution { public int…
- User
Give simple, common, and optimised Java solution
class Solution { public int longestSubarray (int[] nums) {
- Assistant
To solve the problem of finding the longest subarray of 1s after deleting one element from a binary array, you can use a sliding window approach. This method efficiently keeps track of the number of zeros in the current window and adjusts the window size accordingly, allowing you to determine the longest possible subarray of 1s. Here's a simple and optimized Java solution:
class Solution { public int longestSubarray(int[] nums) { int left = 0; int zerosCount = 0; int maxLength = 0; for (int right = 0; right < nums.length; right++) { if (nums[right] == 0) { zerosCount++; } while (zerosCount > 1) { if (nums[left] == 0) { zerosCount--; } left++; } // Calculate the maximum length considering we can delete one zero // The length is (right - left + 1) - 1 to account for deleting one zero maxLength = Math.max(maxLength, right - left); } return maxLength; } }Explanation:
-
Variables Initiation:
leftis the left boundary of the current window.zerosCounttracks the number of zeros in the current window.maxLengthstores the maximum length of the 1s subarray found so far.
-
Iterate Through the Array:
- Use
rightas the right boundary of the window. - Increment
zerosCountwhen a zero is encountered.
- Use
-
Adjust the Window:
- When
zerosCountexceeds 1, move theleftboundary to the right untilzerosCountis 1 again.
- When
-
Calculate Max Length:
- Update
maxLengthusing the length of the current window minus one (to simulate the deletion of one element).
- Update
This approach ensures you examine each element in the array at most twice, making it run in O(n) time complexity, where n is the number of elements in the array. This solution is both simple and optimized for the problem constraints.
-