Skip to content

Commit 1e4d8fc

Browse files
committed
Add solution for max consecuitve ones
1 parent f1fb728 commit 1e4d8fc

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

Diff for: sliding-window/consecutive-ones/README.md

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# 1004. Max Consecutive Ones III
2+
3+
## Description
4+
See https://leetcode.com/problems/max-consecutive-ones-iii/description/
5+
6+
## Problem
7+
Given a binary array `nums` and an integer `k`, return the maximum number of consecutive `1`'s in the array if you can flip at most `k` `0`'s.
8+
9+
## Example 1
10+
11+
```
12+
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
13+
Output: 6
14+
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
15+
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
16+
```
17+
18+
## Example 2
19+
20+
```
21+
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
22+
Output: 10
23+
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
24+
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
25+
```
26+
27+
## Constraints
28+
29+
```
30+
1 <= nums.length <= 105
31+
nums[i] is either 0 or 1.
32+
0 <= k <= nums.length
33+
```

Diff for: sliding-window/consecutive-ones/consecutiveones.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
def longest(nums: list[int], k: int) -> int:
2+
zeros, l = 0, 0
3+
for r, n in enumerate(nums):
4+
zeros += n == 0
5+
if zeros > k:
6+
zeros -= nums[l] == 0
7+
l += 1
8+
return r - l + 1
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from consecutiveones import longest
2+
3+
4+
def test_example_1():
5+
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
6+
k = 2
7+
assert longest(nums, k) == 6
8+
9+
10+
def test_example_2():
11+
nums = [0, 0, 1, 1, 1, 0, 0]
12+
k = 0
13+
assert longest(nums, k) == 3
14+
15+
16+
def test_example_3():
17+
nums = [1, 1, 1, 1, 1]
18+
k = 0
19+
assert longest(nums, k) == 5
20+
21+
22+
def test_example_4():
23+
nums = [0, 0, 0, 0, 0]
24+
k = 5
25+
assert longest(nums, k) == 5
26+
27+
28+
def test_example_5():
29+
nums = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1]
30+
k = 3
31+
assert longest(nums, k) == 11

0 commit comments

Comments
 (0)