Skip to content

Commit 451d4a7

Browse files
committed
Sync LeetCode submission Runtime - 47 ms (28.71%), Memory - 18.2 MB (28.52%)
1 parent 853785c commit 451d4a7

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>&#39;s in the array if you can flip at most one</em> <code>0</code>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
6+
<pre>
7+
<strong>Input:</strong> nums = [1,0,1,1,0]
8+
<strong>Output:</strong> 4
9+
<strong>Explanation:</strong>
10+
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
11+
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
12+
The max number of consecutive ones is 4.
13+
</pre>
14+
15+
<p><strong class="example">Example 2:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> nums = [1,0,1,1,0,1]
19+
<strong>Output:</strong> 4
20+
<strong>Explanation:</strong>
21+
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
22+
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
23+
The max number of consecutive ones is 4.
24+
</pre>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
31+
<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
32+
</ul>
33+
34+
<p>&nbsp;</p>
35+
<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can&#39;t store all numbers coming from the stream as it&#39;s too large to hold in memory. Could you solve it efficiently?</p>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 2: Sliding Window
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
8+
longest_sequence = 0
9+
left, right = 0, 0
10+
num_zeros = 0
11+
12+
while right < len(nums):
13+
if nums[right] == 0:
14+
num_zeros += 1
15+
16+
while num_zeros == 2: # if the window is invalid, contract the window
17+
if nums[left] == 0:
18+
num_zeros -= 1
19+
left += 1
20+
21+
longest_sequence = max(longest_sequence, right - left + 1)
22+
right += 1 # expand the sequence
23+
24+
return longest_sequence
25+

0 commit comments

Comments
 (0)