LeetCode-in-Java

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

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public long maximumSubarraySum(int[] nums, int k) {
        Set<Integer> seen = new HashSet<>();
        long sum = 0;
        long current = 0;
        int i = 0;
        int j = 0;
        while (j < nums.length) {
            while (seen.contains(nums[j])) {
                int val = nums[i++];
                seen.remove(val);
                current -= val;
            }
            seen.add(nums[j]);
            current += nums[j];
            j++;
            if (seen.size() == k) {
                sum = Math.max(sum, current);
                current -= nums[i];
                seen.remove(nums[i]);
                i++;
            }
        }
        return sum;
    }
}