Skip to content

Commit 4508e65

Browse files
Leetcode 1004 answer
1 parent 556ca5a commit 4508e65

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

Leetcode/Leetcode_1004.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
"""
2+
Problem: Max Consecutive Ones III (LeetCode)
3+
4+
Goal:
5+
Given a binary array nums and an integer k,
6+
return the maximum number of consecutive 1s
7+
if you can flip at most k zeros.
8+
9+
Concept:
10+
Sliding Window Technique
11+
12+
---------------------------------------------------
13+
Approach 1: While Loop (Manual right pointer)
14+
---------------------------------------------------
15+
"""
16+
17+
from typing import List
18+
19+
20+
class SolutionWhile:
21+
def longestOnes(self, nums: List[int], k: int) -> int:
22+
l = 0 # left pointer
23+
r = 0 # right pointer
24+
count = 0 # number of zeros in current window
25+
ans = 0 # maximum length
26+
27+
while r < len(nums):
28+
# Step 1: Expand window
29+
if nums[r] == 0:
30+
count += 1
31+
32+
# Step 2: Shrink window if invalid
33+
while count > k:
34+
if nums[l] == 0:
35+
count -= 1
36+
l += 1
37+
38+
# Step 3: Update answer
39+
ans = max(ans, r - l + 1)
40+
41+
# Step 4: Move right pointer
42+
r += 1
43+
44+
return ans
45+
46+
47+
"""
48+
---------------------------------------------------
49+
Approach 2: For Loop (Cleaner and Recommended)
50+
---------------------------------------------------
51+
"""
52+
53+
54+
class SolutionFor:
55+
def longestOnes(self, nums: List[int], k: int) -> int:
56+
l = 0 # left pointer
57+
count = 0 # number of zeros in current window
58+
ans = 0 # maximum length
59+
60+
for r in range(len(nums)):
61+
# Step 1: Expand window
62+
if nums[r] == 0:
63+
count += 1
64+
65+
# Step 2: Shrink window if invalid
66+
while count > k:
67+
if nums[l] == 0:
68+
count -= 1
69+
l += 1
70+
71+
# Step 3: Update answer
72+
ans = max(ans, r - l + 1)
73+
74+
return ans
75+
76+
77+
"""
78+
---------------------------------------------------
79+
Example Usage (for testing)
80+
---------------------------------------------------
81+
"""
82+
83+
if __name__ == "__main__":
84+
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]
85+
k = 2
86+
87+
print("Using While Loop:", SolutionWhile().longestOnes(nums, k))
88+
print("Using For Loop :", SolutionFor().longestOnes(nums, k))
89+
90+
91+
"""
92+
---------------------------------------------------
93+
Key Takeaways:
94+
95+
1. Sliding window expands using 'r'
96+
2. Shrinks using 'l' when condition breaks
97+
3. Maintain constraint: count of zeros <= k
98+
4. Time Complexity: O(n)
99+
5. Space Complexity: O(1)
100+
101+
---------------------------------------------------
102+
"""

0 commit comments

Comments
 (0)