Max Consecutive Ones III

Given an array A of 0s and 1s, we may change up to K values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s.

Example 1:

Example 2:

Note:

  • 1 <= A.length <= 20000
  • 0 <= K <= A.length
  • A[i] is 0 or 1

Solution

Solution 1: Sliding window (dynamic)

class Solution: def longestOnes(self, A: List[int], K: int) -> int: # Time complexity: O(n). # Space complexity: O(1). m, beg = len(A), 0 for end in range(m): if A[end] == 0: K -= 1 if K < 0: if A[beg] == 0: K += 1 beg += 1 return end - beg + 1