Skip to content

Instantly share code, notes, and snippets.

@dicarlomagnus
Created January 6, 2020 20:22
Show Gist options
  • Save dicarlomagnus/f2fdb0f5f955920a4067d8596432fb4b to your computer and use it in GitHub Desktop.
Save dicarlomagnus/f2fdb0f5f955920a4067d8596432fb4b to your computer and use it in GitHub Desktop.
Smallest Subarray with a given sum, in kotlin
/*
Problem Statement #
Given an array of positive numbers and a positive number ‘S’, find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.
Example 1:
Input: [2, 1, 5, 2, 3, 2], S=7
Output: 2
Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].
Example 2:
Input: [2, 1, 5, 2, 8], S=7
Output: 1
Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
Example 3:
Input: [3, 4, 1, 1, 6], S=8
Output: 3
Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].
*/
fun main() {
println(findMinSubArray(intArrayOf(2, 1, 5, 2, 3, 2),7))
println(findMinSubArray(intArrayOf(2, 1, 5, 2, 8),7))
println(findMinSubArray(intArrayOf(3, 4, 1, 1, 6),8))
}
fun findMinSubArray(array: IntArray, s: Int): Int {
var start = 0
var sum = 0
var output = Int.MAX_VALUE
array.forEachIndexed { index, i ->
sum += i
while (sum >= s) {
output = output.coerceAtMost(index - start + 1)
sum -= array[start]
start++
}
}
return if (output == Int.MAX_VALUE) 0 else output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment