From 8a7c5f0a843d4284557c190eece91c3df78452f1 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 17 Nov 2024 20:40:55 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB862.=20Shortest=20Subarray=20?= =?UTF-8?q?with=20Sum=20at=20Least=20K=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/ Signed-off-by: Matej Focko --- kt/shortest-subarray-with-sum-at-least-k.kt | 42 +++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 kt/shortest-subarray-with-sum-at-least-k.kt diff --git a/kt/shortest-subarray-with-sum-at-least-k.kt b/kt/shortest-subarray-with-sum-at-least-k.kt new file mode 100644 index 0000000..ce47a4d --- /dev/null +++ b/kt/shortest-subarray-with-sum-at-least-k.kt @@ -0,0 +1,42 @@ +class Solution { + fun shortestSubarray( + nums: IntArray, + k: Int, + ): Int { + val sums = + nums + .scan(0L) { runningSum, x -> + runningSum + x.toLong() + } + .toList() + + val candidates = ArrayDeque() + + return (0..nums.size) + .map { i -> + var shortestLength = Int.MAX_VALUE + while ( + candidates.isNotEmpty() && + sums[i] - sums[candidates.first()] >= k + ) { + shortestLength = + listOf( + shortestLength, i - candidates.removeFirst(), + ).min() + } + + while ( + candidates.isNotEmpty() && + sums[i] <= sums[candidates.last()] + ) { + candidates.removeLast() + } + + candidates.add(i) + + shortestLength + } + .filter { it < Int.MAX_VALUE } + .minOrNull() ?: -1 + } +}