Skip to content

Instantly share code, notes, and snippets.

@nhudinhtuan
Last active March 30, 2020 08:39
Show Gist options
  • Save nhudinhtuan/d6e8e8b29eb3d7a9f41010920756b7df to your computer and use it in GitHub Desktop.
Save nhudinhtuan/d6e8e8b29eb3d7a9f41010920756b7df 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 be not smaller than k
if n < k:
return -1
left = 0
right = 0
window_sum = 0
while right < n:
# sliding the window to the right
window_sum += arr[right]
right += 1
# check the window size condition and compare the sum
# drop off the left element to avoid oversize
if right-left == k:
highest_sum = max(highest_sum, window_sum)
window_sum -= arr[left]
left += 1
return highest_sum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment