Skip to content

Commit b6d048c

Browse files
authored
ADDED SLIDING WINDOW ALGORITHM TO CALCULATE MAX SUM OF SUBARRAY OF SIZE K OF A ARRAY
1 parent e9e7c96 commit b6d048c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
def max_sum_subarray(arr, k):
2+
# Edge case: if the window size is greater than the array length
3+
if len(arr) < k:
4+
return None
5+
6+
# Compute the sum of the first window
7+
window_sum = sum(arr[:k])
8+
max_sum = window_sum
9+
10+
# Slide the window from left to right
11+
for i in range(k, len(arr)):
12+
# Subtract the element going out of the window and add the new element coming into the window
13+
window_sum += arr[i] - arr[i - k]
14+
max_sum = max(max_sum, window_sum)
15+
16+
return max_sum
17+
18+
# Example usage:
19+
20+
# Example 1: Larger array
21+
arr1 = [4, 3, 10, 2, 8, 6, 7, 1, 9]
22+
k1 = 4
23+
print("Example 1: Maximum sum of subarray of length", k1, "is", max_sum_subarray(arr1, k1))
24+
25+
# Example 2: All elements are negative
26+
arr2 = [-2, -3, -1, -5, -6]
27+
k2 = 2
28+
print("Example 2: Maximum sum of subarray of length", k2, "is", max_sum_subarray(arr2, k2))
29+
30+
# Example 3: Array with all elements equal
31+
arr3 = [5, 5, 5, 5, 5, 5]
32+
k3 = 3
33+
print("Example 3: Maximum sum of subarray of length", k3, "is", max_sum_subarray(arr3, k3))
34+
35+
# Example 4: Small array
36+
arr4 = [1, 2]
37+
k4 = 2
38+
print("Example 4: Maximum sum of subarray of length", k4, "is", max_sum_subarray(arr4, k4))
39+
40+
# Example 5: k greater than the array length
41+
arr5 = [7, 8, 9]
42+
k5 = 5
43+
print("Example 5: Maximum sum of subarray of length", k5, "is", max_sum_subarray(arr5, k5))

0 commit comments

Comments
 (0)