Skip to content

Instantly share code, notes, and snippets.

@ExpandingShapes
Last active October 12, 2021 12:30
Show Gist options
  • Save ExpandingShapes/d81d4834a8d8a4e09bfd066fc7f5b89f to your computer and use it in GitHub Desktop.
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.
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