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 −
- zeros := 0, ans := 0, j := 0
- for each index i and value n in nums, do
- zeros := zeros + (1 when n is same as 0, otherwise 0)
- while zeros > k, do
- zeros := zeros - (1 when nums[j] is same as 0, otherwise 0)
- j := j + 1
- if i - j + 1 > ans, then
- ans := i - j + 1
- return ans
Let us see the following implementation to get better understanding −
Example
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))
Input
[0, 1, 1, 0, 0, 1, 1], 2
Output
6