Last active
December 28, 2021 02:15
-
-
Save nhudinhtuan/97d396adee917869c0fd1e70b0f048ce to your computer and use it in GitHub Desktop.
the highest sum of any k consecutive elements in the array
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code will not work in certain edge cases. Try the following input:
The result should be 12 but your code returns 11.
It's easy to correct though: