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
Inputnums = [1,5,4,2,9,9,9], k = 3
Output15
The valid length-3 subarrays with distinct elements have sums 10, 11, and 15, so the maximum is 15.
Example 2
Inputnums = [4,4,4], k = 3
Output0
The 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

Asked at 10 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate