- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# Program to find length of longest set of 1s by flipping k bits in Python

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

- Related Articles
- Program to find longest number of 1s after swapping one pair of bits in Python
- Program to find length of longest sublist containing repeated numbers by k operations 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 matrix path length in Python
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Program to find longest consecutive run of 1s in binary form of n in Python
- Program to find length of longest increasing subsequence with at least k odd values in Python
- Program to find longest distance of 1s in binary form of a number using Python
- Program to find longest subarray of 1s after deleting one element using 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

Advertisements