Skip to content

Instantly share code, notes, and snippets.

@dicarlomagnus
Created January 6, 2020 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dicarlomagnus/ef7164ac9e3d2ecbde65562e130ca755 to your computer and use it in GitHub Desktop.
Save dicarlomagnus/ef7164ac9e3d2ecbde65562e130ca755 to your computer and use it in GitHub Desktop.
Maximum Sum Subarray of Size K
/*
Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’.
Example 1:
Input: [2, 1, 5, 1, 3, 2], k=3
Output: 9
Explanation: Subarray with maximum sum is [5, 1, 3].
Example 2:
Input: [2, 3, 4, 1, 5], k=2
Output: 7
Explanation: Subarray with maximum sum is [3, 4].
*/
fun main() {
println(findMaxSumSubArray(intArrayOf(2, 1, 5, 1, 3, 2),3))
println(findMaxSumSubArray(intArrayOf(2, 3, 4, 1, 5),2))
}
fun findMaxSumSubArray(array:IntArray, k:Int ):Int{
var sum = 0
var end = 0
var max = 0
array.forEachIndexed { index, i ->
sum += i
if (index >= k-1){
max = sum.coerceAtLeast(max)
sum-= array[end]
end++
}
}
return max
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment