Skip to content

#11517 Added Sliding Window algorithm #11814

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions data_structures/arrays/sliding_window.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def max_sum_subarray(arr: list[int], k: int) -> int:
"""
Finds the maximum sum of a subarray of size k.

Args:
arr (list[int]): List of integers.
k (int): Size of the subarray.

Returns:
int: Maximum sum of a subarray of size k or 0 if no valid sum found.

>>> max_sum_subarray([2, 1, 5, 1, 3, 2], 3)
9
>>> max_sum_subarray([2, 3, 4, 1, 5], 2)
7
>>> max_sum_subarray([1, 2, 3], 5)
0 # Example case where k is larger than the array
"""
n = len(arr)
if n < k: # Edge case: if window size is larger than array size
return 0 # Consider returning 0 instead of -1

max_sum = float("-inf")
window_sum = sum(arr[:k]) # Sum of the first window

for i in range(n - k):
window_sum = window_sum - arr[i] + arr[i + k]
max_sum = max(max_sum, window_sum)

return int(max_sum) if max_sum != float("-inf") else 0
Loading