Skip to content

Commit 630f717

Browse files
#11517 Added Sliding Window algorithm
Signed-off-by: Muhammad Arshad <[email protected]>
1 parent fcf82a1 commit 630f717

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def max_sum_subarray(arr: list[int], k: int) -> int:
2+
"""
3+
Finds the maximum sum of a subarray of size k.
4+
5+
Args:
6+
arr (list[int]): List of integers.
7+
k (int): Size of the subarray.
8+
9+
Returns:
10+
int: Maximum sum of a subarray of size k or 0 if no valid sum found.
11+
12+
>>> max_sum_subarray([2, 1, 5, 1, 3, 2], 3)
13+
9
14+
>>> max_sum_subarray([2, 3, 4, 1, 5], 2)
15+
7
16+
>>> max_sum_subarray([1, 2, 3], 5)
17+
0 # Example case where k is larger than the array
18+
"""
19+
n = len(arr)
20+
if n < k: # Edge case: if window size is larger than array size
21+
return 0 # Consider returning 0 instead of -1
22+
23+
max_sum = float("-inf")
24+
window_sum = sum(arr[:k]) # Sum of the first window
25+
26+
for i in range(n - k):
27+
window_sum = window_sum - arr[i] + arr[i + k]
28+
max_sum = max(max_sum, window_sum)
29+
30+
return int(max_sum) if max_sum != float("-inf") else 0

0 commit comments

Comments
 (0)