Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable.

Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable.
def longest_ones(a, k):
    l = zeros = best = 0
    for r, x in enumerate(a):
        zeros += x == 0
        while zeros > k:
            zeros -= a[l] == 0
            l += 1
        best = max(best, r - l + 1)
    return best
print(longest_ones([1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1], 2))
What is printed?
  1. A. 7
  2. B. 6
  3. C. 5
  4. D. 3

Correct answer: A. 7

Keep at most k zeros in the window and shrink from the left when a third zero enters. The best window is indices 2..8 = [1, 1, 0, 0, 1, 1, 1], length 7. Using r − l (forgetting + 1) prints 6, shrinking when zeros ≥ k allows only one flip (5), and ignoring flips gives the plain longest run 3.

More Coding Interview Problems questions

Exams that ask this topic