Open songyy5517 opened 6 months ago
Approach: Sliding Window
left = 0
: the leftnmost element, forming the longest subarray with the current element;max_len = 0
: the global maximum length;k = 1
: the number of zeros allowed to be in the array. k
by 1;
(2)If k < 0
, then move the left pointer to the right until the window only contains one zero.
(3)Calculate the length of the current window, and update the global maximum.max_len
.Complexity Analysis
class Solution {
public int longestSubarray(int[] nums) {
// Intuition: Sliding window. this problem is similar the previous one.
// where we can see k as 1. So this problem can also transformed
// into finding the longest subarray including just one zero.
// 1. Exception handling
if (nums == null || nums.length == 1)
return 0;
// 2. Define variables
int left = 0;
int max_len = 1;
int k = 1;
// 3. Loop through the array
for (int i = 0; i < nums.length; i++){
// Update the right pointer
if (nums[i] == 0)
k --;
// Update the left pointer
while (k < 0){
if (nums[left ++] == 0)
k ++;
}
max_len = Math.max(max_len, i - left + 1);
}
return max_len - 1;
}
}
2024/5/14
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:
Example 2:
Example 3:
Intuition This problem is similar to the previous one where we can consider k as 1. A simple idea is to iterate over the array with a sliding window. For each element we come across, we consider it as the end of the subarray and also the rightmost element of the window. Meanwhile, we keep a left pointer to form the longest valid subarray with the current element. Then, we calclulate the window length and update the global maximum value.