LeetCode solutions

1046. Max Consecutive Ones III

My accepted Python solution to LeetCode problem 1046, Max Consecutive Ones III, running in 83ms.

  • Difficulty: Medium
  • Python
  • Runtime 83ms
  • Memory 20MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 83ms, memory 20MB, accepted 2025-12-30.

python
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        left = 0
        zeros = 0
        max_len = 0
        
        for right in range(len(nums)):
            if nums[right] == 0:
                zeros += 1
            
            while zeros > k:
                if nums[left] == 0:
                    zeros -= 1
                left += 1
            
            max_len = max(max_len, right - left + 1)
        
        return max_len

Source