Skip to content

Commit 037b007

Browse files
committed
fixed size sliding window technique
1 parent 0d9804a commit 037b007

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
Fixed-Size Sliding Window Algorithm
3+
4+
This module contains an implementation of the fixed-size
5+
sliding window algorithm with doctests.
6+
7+
Examples:
8+
>>> max_sum_subarray([1, 2, 3, 4, 5], 3)
9+
12
10+
11+
>>> max_sum_subarray([2, 1, 5, 1, 3, 2], 4)
12+
11
13+
"""
14+
15+
16+
def max_sum_subarray(arr: list[int], k: int) -> int:
17+
"""
18+
Find the maximum sum of any subarray of size `k`.
19+
20+
Args:
21+
arr: The input array of integers.
22+
k: The size of the subarray.
23+
24+
Returns:
25+
The maximum sum of a subarray of size `k`.
26+
27+
Raises:
28+
ValueError: If the length of the array is less than `k`.
29+
30+
Examples:
31+
>>> max_sum_subarray([1, 2, 3, 4, 5], 3)
32+
12
33+
34+
>>> max_sum_subarray([2, 1, 5, 1, 3, 2], 4)
35+
11
36+
37+
>>> max_sum_subarray([1, 2], 3)
38+
Traceback (most recent call last):
39+
...
40+
ValueError: Array length must be at least as large as the window size.
41+
"""
42+
if len(arr) < k:
43+
raise ValueError("Array length must be at least as large as the window size.")
44+
45+
max_sum = float('-inf')
46+
window_sum = sum(arr[:k])
47+
max_sum = max(max_sum, window_sum)
48+
49+
for i in range(len(arr) - k):
50+
window_sum = window_sum - arr[i] + arr[i + k]
51+
max_sum = max(max_sum, window_sum)
52+
53+
return max_sum
54+
55+
56+
if __name__ == "__main__":
57+
import doctest
58+
59+
doctest.testmod()

0 commit comments

Comments
 (0)