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:
Matej Focko 2024-11-19 22:25:09 +01:00
parent 700a8d0107
commit cb85787112
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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
}
}