Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Last active March 30, 2020 05:51
Show Gist options
  • Save nhudinhtuan/c4e3b0d966073f54ba07ebfb3aed7066 to your computer and use it in GitHub Desktop.
Save nhudinhtuan/c4e3b0d966073f54ba07ebfb3aed7066 to your computer and use it in GitHub Desktop.
the highest sum of any k consecutive elements in the array
def highestSum(arr, k):
highest_sum = float('-inf')
n = len(arr)
# n must not be smaller than k
if n < k:
return -1
# subarray starts at i
for i in range(n - k + 1):
# calculate sum of the subarray
current_sum = 0
for j in range(k):
current_sum += arr[i + j]
# compare the sum
highest_sum = max(highest_sum, current_sum)
return highest_sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment