LeetCode in Kotlin

2461. Maximum Sum of Distinct Subarrays With Length K

Medium

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

Return the maximum subarray sum of all the subarrays that meet the conditions__. If no subarray meets the conditions, return 0.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,5,4,2,9,9,9], k = 3

Output: 15

Explanation: The subarrays of nums with length 3 are:

We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions

Example 2:

Input: nums = [4,4,4], k = 3

Output: 0

Explanation: The subarrays of nums with length 3 are:

Constraints:

Solution

class Solution {
    fun maximumSubarraySum(nums: IntArray, k: Int): Long {
        val seen: MutableSet<Int> = HashSet()
        var sum: Long = 0
        var current: Long = 0
        var i = 0
        var j = 0
        while (j < nums.size) {
            while (seen.contains(nums[j])) {
                val `val` = nums[i++]
                seen.remove(`val`)
                current -= `val`.toLong()
            }
            seen.add(nums[j])
            current += nums[j].toLong()
            j++
            if (seen.size == k) {
                sum = Math.max(sum, current)
                current -= nums[i].toLong()
                seen.remove(nums[i])
                i++
            }
        }
        return sum
    }
}