Last active
October 12, 2021 12:30
-
-
Save ExpandingShapes/d81d4834a8d8a4e09bfd066fc7f5b89f to your computer and use it in GitHub Desktop.
Given an array of n integers and size k, where k < n, find the maximum sum of 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
fun findMaximumSum(a: IntArray, k: Int): Int { | |
var currentSum: Int = 0 | |
var maximumSum: Int | |
for (i in 0 until k) { | |
currentSum += a[i] | |
} | |
maximumSum = currentSum | |
for (i in k until a.size) { | |
// Discard the left most element | |
currentSum -= a[i - k] | |
// Included the current element | |
currentSum += a[i] | |
if (maximumSum < currentSum) { | |
maximumSum = currentSum | |
} | |
} | |
return maximumSum | |
} | |
fun main() { | |
val a = intArrayOf(1, 4, 2, 10, 2, 3, 1, 0, 20) | |
val k = 4 | |
println("Maximum sum: " + findMaximumSum(a, k)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment