Practice › Sliding Window
Longest Run of 1s After Deleting One
Medium · Sliding Window · Asked at Meta, Amazon, Microsoft
You must delete exactly one element of the binary array. Print the length of the longest non-empty run of consecutive 1s possible afterwards, or 0 if there is none.
Input
First line: n. Second line: n space-separated integers.
Output
The longest run of 1s after one deletion.
Constraints
- 1 ≤ n ≤ 10^5
- a[i] is 0 or 1
Find the longest window containing at most one 0 (shrink from the left when a second 0 enters). The deleted element is that 0 — or, if the window has no 0, any one element — so the answer is the window length minus 1.
Example 1
Input
4 1 1 0 1
Output
3
Example 2
Input
9 0 1 1 1 0 1 1 0 1
Output
5
Hints
- After deleting one 0, two runs of 1s on either side of it join.
- Look for the longest window that contains at most one 0.
- One element must be deleted, so subtract 1 from the window length.
Approach
Sliding window [l, i] with zeros = number of 0s inside. Extend i; while zeros > 1, move l right (decreasing zeros when a 0 leaves). The longest window length minus one is the answer: delete its 0, or, if it is all 1s, delete one of its 1s. An array of all 1s therefore gives n − 1.
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for (auto &x : a) cin >> x;
int l = 0, zeros = 0, best = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) zeros++;
while (zeros > 1)
if (a[l++] == 0) zeros--;
best = max(best, i - l);
}
cout << best << "\n";
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
n = data[0]
a = data[1 : 1 + n]
l = zeros = best = 0
for i, x in enumerate(a):
if x == 0:
zeros += 1
while zeros > 1:
if a[l] == 0:
zeros -= 1
l += 1
best = max(best, i - l)
print(best)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
in.nextToken();
a[i] = (int) in.nval;
}
int l = 0, zeros = 0, best = 0;
for (int i = 0; i < n; i++) {
if (a[i] == 0) zeros++;
while (zeros > 1)
if (a[l++] == 0) zeros--;
best = Math.max(best, i - l);
}
System.out.println(best);
}
}Solve Longest Run of 1s After Deleting One online · All practice problems