Maximum Sum of Distinct Subarrays With Length K
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:
- The length of the subarray is
k. - All the elements of the subarray are distinct.
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 = 3Output
15The valid length-3 subarrays with distinct elements have sums 10, 11, and 15, so the maximum is 15.
Example 2
Input
nums = [4,4,4], k = 3Output
0The only length-3 subarray contains repeated 4s, so no subarray meets the conditions.
Constraints
- 1 <= k <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5