Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Last active December 28, 2021 02:15
Show Gist options
  • Save nhudinhtuan/97d396adee917869c0fd1e70b0f048ce to your computer and use it in GitHub Desktop.
Save nhudinhtuan/97d396adee917869c0fd1e70b0f048ce 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
# Compute sum of first window of size k
window_sum = sum([arr[i] for i in range(k)])
# Compute sums of remaining windows by
# removing first element of previous
# window and adding last element of
# current window.
for i in range(n - k):
window_sum = window_sum - arr[i] + arr[i + k]
highest_sum = max(highest_sum, window_sum)
return highest_sum
@DmitriiSer
Copy link

This code will not work in certain edge cases. Try the following input:

arr = [2, 3, 7, 1, 1, 1]
k = 3

The result should be 12 but your code returns 11.

It's easy to correct though:

  1. Remove line #2
  2. Add the following code to line #11:
highest_sum  = window_sum

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment