Skip to content

Created max_sum_sliding_window in Python/other #3065

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

Merged
merged 7 commits into from
Oct 9, 2020
Merged
Changes from 2 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
43 changes: 43 additions & 0 deletions other/max_sum_sliding_window.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""
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.
"""
import sys
from typing import List


def max_sum(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(arr, k)
24
>>> k = 10
>>> max_sum(arr,k)
Invalid input
-1
"""
if len(array) < k or k < 0:
print("Invalid input")
return -1
max_sum = -sys.maxsize
current_sum = sum(array[:k])
for i in range(len(array) - k):
current_sum = current_sum - array[i] + array[i + k]
current_sum = max(max_sum, current_sum)
return current_sum


if __name__ == "__main__":
from doctest import testmod
from random import randint

testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum(array,k)}")