1- """
2- Question:
3- Given a binary array nums and an integer k, find the length of the longest subarray containing 1s after flipping at most k zeros.
4-
5- Example:
6- Input: nums = [1,0,1,1,0,1], k = 1
7- Output: 4
8- Explanation:
9- Flip the first 0 at index 1 -> subarray [1,1,1,1] has length 4
10- """
11-
121from typing import List
132
14-
153class LongestOnesAfterReplacement :
16- def longest_ones (self , nums : List [int ], k : int ) -> int :
17- left = 0 # Left pointer of sliding window
18- max_len = 0 # Tracks maximum window length
19- zeros_count = 0 # Count of zeros in current window
4+ """
5+ Problem:
6+ Given a binary array and an integer max_zero_flips, find the length of the
7+ longest subarray containing only 1s after flipping at most max_zero_flips zeros.
8+
9+ Example:
10+ >>> solver = LongestOnesAfterReplacement()
11+ >>> solver.longest_ones([1, 0, 1, 1, 0, 1], 1)
12+ 4
13+ """
14+
15+ def longest_ones (self , nums : List [int ], max_zero_flips : int ) -> int :
16+ left = 0
17+ max_len = 0
18+ zeros_count = 0
2019
2120 for right in range (len (nums )):
2221 if nums [right ] == 0 :
2322 zeros_count += 1
2423
25- # Shrink window if zeros exceed k
26- while zeros_count > k :
24+ while zeros_count > max_zero_flips :
2725 if nums [left ] == 0 :
2826 zeros_count -= 1
2927 left += 1
@@ -33,9 +31,8 @@ def longest_ones(self, nums: List[int], k: int) -> int:
3331 return max_len
3432
3533
36- # Example dry run
3734if __name__ == "__main__" :
38- nums = [1 , 0 , 1 , 1 , 0 , 1 ]
39- k = 1
4035 solver = LongestOnesAfterReplacement ()
41- print ("Longest Ones After Replacement:" , solver .longest_ones (nums , k ))
36+ print ("Longest Ones After Replacement:" ,
37+ solver .longest_ones ([1 , 0 , 1 , 1 , 0 , 1 ], 1 ))
38+
0 commit comments