|
| 1 | +""" |
| 2 | +Given an array of integer elements and an integer 'k', we are required to find the |
| 3 | +maximum sum of 'k' consecutive elements in the array. |
| 4 | +
|
| 5 | +Instead of using a nested for loop, in a Brute force approach we will use a technique |
| 6 | +called 'Window sliding technique' where the nested loops can be converted to a single |
| 7 | +loop to reduce time complexity. |
| 8 | +""" |
| 9 | +from typing import List |
| 10 | + |
| 11 | + |
| 12 | +def max_sum_in_array(array: List[int], k: int) -> int: |
| 13 | + """ |
| 14 | + Returns the maximum sum of k consecutive elements |
| 15 | + >>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] |
| 16 | + >>> k = 4 |
| 17 | + >>> max_sum_in_array(arr, k) |
| 18 | + 24 |
| 19 | + >>> k = 10 |
| 20 | + >>> max_sum_in_array(arr,k) |
| 21 | + Traceback (most recent call last): |
| 22 | + ... |
| 23 | + ValueError: Invalid Input |
| 24 | + >>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2] |
| 25 | + >>> k = 4 |
| 26 | + >>> max_sum_in_array(arr, k) |
| 27 | + 27 |
| 28 | + """ |
| 29 | + if len(array) < k or k < 0: |
| 30 | + raise ValueError("Invalid Input") |
| 31 | + max_sum = current_sum = sum(array[:k]) |
| 32 | + for i in range(len(array) - k): |
| 33 | + current_sum = current_sum - array[i] + array[i + k] |
| 34 | + max_sum = max(max_sum, current_sum) |
| 35 | + return max_sum |
| 36 | + |
| 37 | + |
| 38 | +if __name__ == "__main__": |
| 39 | + from doctest import testmod |
| 40 | + from random import randint |
| 41 | + |
| 42 | + testmod() |
| 43 | + array = [randint(-1000, 1000) for i in range(100)] |
| 44 | + k = randint(0, 110) |
| 45 | + print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}") |
0 commit comments