Skip to content

Commit d16c462

Browse files
author
Adam Lin
committed
use two ptr and sliding window
1 parent e80d2b7 commit d16c462

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

1493_longestSubarray.cpp

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class Solution {
2+
public:
3+
int longestSubarray(vector<int>& nums) {
4+
// Initialize two pointers and variables to track window size and deleted zeros
5+
int ptrL = 0, ptrR = 0, maxWindow = 0, maxDeleted = 0;
6+
7+
// 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.
65+
*/

0 commit comments

Comments
 (0)