Last active
February 6, 2020 06:39
-
-
Save drem-darios/901d2e7d15f68ed28846e9c55571dd7a to your computer and use it in GitHub Desktop.
Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# By Drem | |
def max_sub_array_of_size_k(k, arr): | |
maximumSum = 0 | |
currentMaximumSum = 0 | |
subArrayStart = 0 | |
for subArrayEnd in range(len(arr)): | |
maximumSum += arr[subArrayEnd] | |
if subArrayEnd >= k - 1: | |
if maximumSum > currentMaximumSum: | |
currentMaximumSum = maximumSum | |
maximumSum -= arr[subArrayStart] | |
subArrayStart+=1 | |
return currentMaximumSum | |
def main(): | |
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2]))) | |
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5]))) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment