You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// Iterate through the array using the right pointer
8
+
for(int ptrR = 0; ptrR < nums.size(); ++ptrR){
9
+
// If the current element is 0, increment the count of deleted zeros
10
+
if(nums[ptrR] == 0){
11
+
maxDeleted++;
12
+
}
13
+
14
+
// If more than one zero is in the current window, move the left pointer to shrink the window
15
+
while(maxDeleted > 1){
16
+
if(nums[ptrL] == 0){
17
+
maxDeleted--; // Reduce the count of deleted zeros as we move past a zero
18
+
}
19
+
ptrL++; // Move the left pointer to the right
20
+
}
21
+
22
+
// Calculate the maximum window length (excluding one zero) by updating maxWindow
23
+
maxWindow = max(maxWindow, ptrR - ptrL);
24
+
}
25
+
26
+
// Return the maximum window length found
27
+
return maxWindow;
28
+
}
29
+
};
30
+
31
+
/*
32
+
Explanation with Picture:
33
+
34
+
Consider the array: [1, 1, 0, 1, 1, 0, 1, 1, 1]
35
+
36
+
We use two pointers, ptrL and ptrR, to represent the sliding window:
37
+
38
+
Initial state:
39
+
40
+
ptrL -> 0
41
+
ptrR -> 0
42
+
[1, 1, 0, 1, 1, 0, 1, 1, 1]
43
+
44
+
As ptrR moves to the right, it expands the window, and we keep track of zeros encountered:
45
+
46
+
Step 1:
47
+
ptrR moves to index 2 (nums[2] == 0)
48
+
Count of zeros (maxDeleted) = 1
49
+
50
+
Step 2:
51
+
ptrR moves to index 5 (nums[5] == 0)
52
+
Count of zeros (maxDeleted) = 2
53
+
Since maxDeleted > 1, ptrL will move right to reduce the window size:
54
+
55
+
ptrL -> 3
56
+
57
+
Updated state:
58
+
ptrL at index 3
59
+
ptrR at index 5
60
+
61
+
Continue expanding the window until ptrR reaches the end, while ensuring only one zero is deleted in the current window. The goal is to find the largest possible window length (excluding one zero).
62
+
63
+
Final result:
64
+
The longest subarray with at most one zero deleted is of length 5.
0 commit comments