Maximum Sum of Distinct Subarrays With Length K

Medium Topics Company Tags

Among all contiguous subarrays of nums with exactly k elements and no repeated values, return the largest sum. If there is no such subarray, return 0.

Example 1:

Input: nums = [2,3,2,5]
k = 3

Output: 10

Explanation: The window [2,3,2] repeats 2 and is invalid. The window [3,2,5] has three distinct values and sum 10, so the result is 10.

Example 2:

Input: nums = [7,7]
k = 2

Output: 0

Explanation: The only length-2 window contains two copies of 7. No valid window exists, so return 0.

Example 3:

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

Output: 4

Explanation: Every single-element window has distinct values. The largest such sum is the element 4.

Constraints:

  • 1 <= nums.length <= 100000
  • 1 <= nums[i] <= 100000
  • 1 <= k <= nums.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.