kt: add «862. Shortest Subarray with Sum at Least K»
URL: https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
1524366e77
commit
8a7c5f0a84
1 changed files with 42 additions and 0 deletions
42
kt/shortest-subarray-with-sum-at-least-k.kt
Normal file
42
kt/shortest-subarray-with-sum-at-least-k.kt
Normal file
|
@ -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<Int>()
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue