- Related Questions & Answers
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Program to find length of longest substring with character count of at least k in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest increasing subsequence with at least k odd values in Python
- Program to find length of longest diminishing word chain in Python?
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence of three strings in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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

Advertisements