Matej Focko
cb85787112
URL: https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/ Signed-off-by: Matej Focko <me@mfocko.xyz>
33 lines
705 B
Kotlin
33 lines
705 B
Kotlin
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
|
|
}
|
|
}
|