forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax_sum_sliding_window.py
48 lines (41 loc) · 1.37 KB
/
max_sum_sliding_window.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Given an array of integer elements and an integer 'k', we are required to find the
maximum sum of 'k' consecutive elements in the array.
Instead of using a nested for loop, in a Brute force approach we will use a technique
called 'Window sliding technique' where the nested loops can be converted to a single
loop to reduce time complexity.
"""
from __future__ importannotations
defmax_sum_in_array(array: list[int], k: int) ->int:
"""
Returns the maximum sum of k consecutive elements
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
>>> k = 4
>>> max_sum_in_array(arr, k)
24
>>> k = 10
>>> max_sum_in_array(arr,k)
Traceback (most recent call last):
...
ValueError: Invalid Input
>>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]
>>> k = 4
>>> max_sum_in_array(arr, k)
27
"""
iflen(array) <kork<0:
raiseValueError("Invalid Input")
max_sum=current_sum=sum(array[:k])
foriinrange(len(array) -k):
current_sum=current_sum-array[i] +array[i+k]
max_sum=max(max_sum, current_sum)
returnmax_sum
if__name__=="__main__":
fromdoctestimporttestmod
fromrandomimportrandint
testmod()
array= [randint(-1000, 1000) foriinrange(100)]
k=randint(0, 110)
print(
f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array, k)}"
)