Skip to content

Commit 276e846

Browse files
committed
Sync LeetCode submission Runtime - 59 ms (68.04%), Memory - 18.3 MB (54.24%)
1 parent 451d4a7 commit 276e846

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<p>Given a binary array <code>nums</code> and an integer <code>k</code>, return <em>the maximum number of consecutive </em><code>1</code><em>&#39;s in the array if you can flip at most</em> <code>k</code> <code>0</code>&#39;s.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
8+
<strong>Output:</strong> 6
9+
<strong>Explanation:</strong> [1,1,1,0,0,<u><strong>1</strong>,1,1,1,1,<strong>1</strong></u>]
10+
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
16+
<strong>Output:</strong> 10
17+
<strong>Explanation:</strong> [0,0,<u>1,1,<strong>1</strong>,<strong>1</strong>,1,1,1,<strong>1</strong>,1,1</u>,0,0,0,1,1,1,1]
18+
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
19+
</pre>
20+
21+
<p>&nbsp;</p>
22+
<p><strong>Constraints:</strong></p>
23+
24+
<ul>
25+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
26+
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
27+
<li><code>0 &lt;= k &lt;= nums.length</code></li>
28+
</ul>
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Approach: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def longestOnes(self, nums: List[int], k: int) -> int:
8+
left = 0
9+
zeros_count = 0
10+
max_consecutive = 0
11+
12+
for right in range(len(nums)):
13+
if nums[right] == 0:
14+
zeros_count += 1
15+
16+
# If we have more zeros than allowed, shrink the window from the left
17+
while zeros_count > k:
18+
if nums[left] == 0:
19+
zeros_count -= 1
20+
left += 1
21+
22+
max_consecutive = max(max_consecutive, right - left + 1)
23+
24+
return max_consecutive

0 commit comments

Comments
 (0)