Skip to content

Commit e9ba24f

Browse files
committed
Merge branch 'data_structure/sliding_window/examples-' of https://github.com/lydia321/Python into data_structure/sliding_window/examples-
2 parents 288543b + dcd35f2 commit e9ba24f

File tree

3 files changed

+19
-13
lines changed

3 files changed

+19
-13
lines changed

data_structures/sliding_window/longest_substring_two_distinct.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,29 @@ def length_of_longest_substring_two_distinct(string: str) -> int:
2222
n = len(s)
2323
if n == 0:
2424
return 0
25-
25+
2626
# Dictionary to store the last occurrence of each character
2727
char_map = {}
2828
left = 0
2929
max_length = 0
30-
30+
3131
# Sliding window approach
3232
for right in range(n):
3333
char_map[s[right]] = right
34-
34+
3535
# If we have more than two distinct characters
3636
if len(char_map) > 2:
3737
# Remove the leftmost character
3838
del_idx = min(char_map.values())
3939
del char_map[s[del_idx]]
4040
left = del_idx + 1
41-
41+
4242
max_length = max(max_length, right - left + 1)
43-
43+
4444
return max_length
4545

46+
4647
if __name__ == "__main__":
4748
import doctest
49+
4850
doctest.testmod()

data_structures/sliding_window/max_sum_subarray.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,20 @@ def max_sum_subarray(array: List[int], subarray_length: int) -> int:
2626
if n < k or k <= 0:
2727
print("Invalid input: k is larger than the array size or non-positive")
2828
return None
29-
29+
3030
# Calculate the sum of the first window of size k
3131
window_sum = sum(arr[:k])
3232
max_sum = window_sum
33-
33+
3434
# Slide the window from start to end of the array
3535
for i in range(n - k):
3636
window_sum = window_sum - arr[i] + arr[i + k]
3737
max_sum = max(max_sum, window_sum)
38-
38+
3939
return max_sum
4040

41+
4142
if __name__ == "__main__":
4243
import doctest
44+
4345
doctest.testmod()

data_structures/sliding_window/min_subarray_len.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,20 @@ def min_subarray_len(target_sum: int, numbers: List[int]) -> int:
2626
n = len(nums)
2727
left = 0
2828
current_sum = 0
29-
min_length = float('inf')
30-
29+
min_length = float("inf")
30+
3131
for right in range(n):
3232
current_sum += nums[right]
33-
33+
3434
while current_sum >= target:
3535
min_length = min(min_length, right - left + 1)
3636
current_sum -= nums[left]
3737
left += 1
38-
39-
return min_length if min_length != float('inf') else 0
38+
39+
return min_length if min_length != float("inf") else 0
40+
4041

4142
if __name__ == "__main__":
4243
import doctest
44+
4345
doctest.testmod()

0 commit comments

Comments
 (0)