Last active
March 30, 2020 05:51
-
-
Save nhudinhtuan/c4e3b0d966073f54ba07ebfb3aed7066 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 | |
# 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