Created
January 6, 2020 20:23
-
-
Save dicarlomagnus/ef7164ac9e3d2ecbde65562e130ca755 to your computer and use it in GitHub Desktop.
Maximum Sum Subarray of Size K
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
/* | |
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