Skip to content

Commit fb74d55

Browse files
committed
Initial commit
1 parent b59b9ba commit fb74d55

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Longest Subarray with Ones after Replacement (hard)
2+
# Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.
3+
4+
# Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
5+
# Output: 6
6+
# Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6.
7+
8+
def length_of_longest_substring(arr, k):
9+
window_start, max_length, max_ones_count = 0, 0, 0
10+
11+
# Try to extend the range [window_start, window_end]
12+
for window_end in range(len(arr)):
13+
if arr[window_end] == 1:
14+
max_ones_count += 1
15+
16+
# Current window size is from window_start to window_end, overall we have a maximum of 1s
17+
# repeating 'max_ones_count' times, this means we can have a window with 'max_ones_count' 1s
18+
# and the remaining are 0s which should replace with 1s.
19+
# now, if the remaining 0s are more than 'k', it is the time to shrink the window as we
20+
# are not allowed to replace more than 'k' 0s
21+
if (window_end - window_start + 1 - max_ones_count) > k:
22+
if arr[window_start] == 1:
23+
max_ones_count -= 1
24+
window_start += 1
25+
26+
max_length = max(max_length, window_end - window_start + 1)
27+
return max_length
28+
29+
30+
def main():
31+
print(length_of_longest_substring([0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], 2))
32+
print(length_of_longest_substring(
33+
[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3))
34+
35+
36+
main()

0 commit comments

Comments
 (0)