Skip to content

Commit 17bcf15

Browse files
authored
Create longest-subarray-of-1s-after-deleting-one-element.cpp
1 parent 10c08eb commit 17bcf15

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int longestSubarray(vector<int>& nums) {
7+
int count = 0, left = 0, right = 0;
8+
for (; right < nums.size(); ++right) {
9+
count += (nums[right] == 0);
10+
if (count >= 2) {
11+
count -= (nums[left++] == 0);
12+
}
13+
}
14+
return (right - left) - 1;
15+
}
16+
};
17+
18+
// Time: O(n)
19+
// Space: O(1)
20+
class Solution2 {
21+
public:
22+
int longestSubarray(vector<int>& nums) {
23+
int result = 0, count = 0, left = 0;
24+
for (int right = 0; right < nums.size(); ++right) {
25+
count += (nums[right] == 0);
26+
while (count >= 2) {
27+
count -= (nums[left++] == 0);
28+
}
29+
result = max(result, right - left + 1);
30+
}
31+
return result - 1;
32+
}
33+
};

0 commit comments

Comments
 (0)