kt: add «2461. Maximum Sum of Distinct Subarrays With Length K»
URL: https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
700a8d0107
commit
cb85787112
1 changed files with 33 additions and 0 deletions
33
kt/maximum-sum-of-distinct-subarrays-with-length-k.kt
Normal file
33
kt/maximum-sum-of-distinct-subarrays-with-length-k.kt
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
class Solution {
|
||||||
|
fun maximumSubarraySum(
|
||||||
|
nums: IntArray,
|
||||||
|
k: Int,
|
||||||
|
): Long {
|
||||||
|
var maximum = 0L
|
||||||
|
|
||||||
|
var (l, r) = 0 to 0
|
||||||
|
var runningSum = 0
|
||||||
|
|
||||||
|
val seen = mutableMapOf<Int, Int>()
|
||||||
|
while (r < nums.size) {
|
||||||
|
val x = nums[r]
|
||||||
|
|
||||||
|
val lastSeen = seen.getOrElse(x) { -1 }
|
||||||
|
while (l <= lastSeen || r - l + 1 > k) {
|
||||||
|
runningSum -= nums[l]
|
||||||
|
l += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
seen.put(x, r)
|
||||||
|
runningSum += nums[r]
|
||||||
|
|
||||||
|
if (end - begin + 1 == k) {
|
||||||
|
maximum = listOf(maximum, runningSum).max()
|
||||||
|
}
|
||||||
|
|
||||||
|
r += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return maximum
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue