Suppose we have a binary list, so here only 1s and 0s are available and we also have another number k. We can set at most k 0s to 1s, we have to find the length of the longest sublist containing all 1s.
So, if the input is like nums = [0, 1, 1, 0, 0, 1, 1] k = 2, then the output will be 6, as we can set the two middle 0s to 1s and then the list becomes [0, 1, 1, 1, 1, 1, 1].
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums, k): zeros = 0 ans = 0 j = 0 for i, n in enumerate(nums): zeros += n == 0 while zeros > k: zeros -= nums[j] == 0 j += 1 if i - j + 1 > ans: ans = i - j + 1 return ans ob = Solution() nums = [0, 1, 1, 0, 0, 1, 1] k = 2 print(ob.solve(nums, k))
[0, 1, 1, 0, 0, 1, 1], 2
6