Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Last active February 6, 2020 06:39
Show Gist options
  • Save drem-darios/901d2e7d15f68ed28846e9c55571dd7a to your computer and use it in GitHub Desktop.
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’.
# 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