From fd6d1ea79513f19fdab37110a901dd95e71233e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B8=D1=85=D0=B0=D0=B8=D0=BB=20=D0=92=D0=B0=D1=81?= =?UTF-8?q?=D0=B8=D0=BB=D1=8C=D0=B5=D0=B2?= Date: Thu, 9 Oct 2025 20:03:29 +0300 Subject: [PATCH] feat: [LeetCode #1004] Max Consecutive Ones Iii MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Тип: sliding-window Сложность: medium Временная сложность: O(n) Пространственная сложность: O(1) - Ссылка: https://leetcode.com/problems/max-consecutive-ones-iii/ --- .../max_consecutive_ones_iii/__init__.py | 0 .../max_consecutive_ones_iii/solution.py | 20 +++++++++++++++++++ tests/test_max_consecutive_ones_iii.py | 14 +++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 src/sliding_window/max_consecutive_ones_iii/__init__.py create mode 100644 src/sliding_window/max_consecutive_ones_iii/solution.py create mode 100644 tests/test_max_consecutive_ones_iii.py diff --git a/src/sliding_window/max_consecutive_ones_iii/__init__.py b/src/sliding_window/max_consecutive_ones_iii/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/sliding_window/max_consecutive_ones_iii/solution.py b/src/sliding_window/max_consecutive_ones_iii/solution.py new file mode 100644 index 0000000..128ab4c --- /dev/null +++ b/src/sliding_window/max_consecutive_ones_iii/solution.py @@ -0,0 +1,20 @@ +from typing import List + + +class Solution: + def longestOnes(self, nums: List[int], k: int) -> int: + left = 0 + max_length = 0 + zero_counter = 0 + + for index in range(len(nums)): + if nums[index] == 0: + zero_counter += 1 + while zero_counter > k: + if nums[left] == 0: + zero_counter -= 1 + left += 1 + + max_length = max(max_length, index - left + 1) + + return max_length diff --git a/tests/test_max_consecutive_ones_iii.py b/tests/test_max_consecutive_ones_iii.py new file mode 100644 index 0000000..af7c399 --- /dev/null +++ b/tests/test_max_consecutive_ones_iii.py @@ -0,0 +1,14 @@ +import pytest +from src.sliding_window.max_consecutive_ones_iii.solution import Solution + + +@pytest.mark.parametrize( + "nums, k, expected", + [ + ([1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], 2, 6), + ([0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], 3, 10), + ], +) +def test_longest_ones(nums, k, expected): + solution = Solution() + assert solution.longestOnes(nums, k) == expected