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 have length `k` and whose elements are all distinct. Return that maximum, or `0` if no subarray meets the conditions.

30:00

Maximum Sum of Distinct Subarrays With Length K
medium
Free written solution
Topics
Companies

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that have length k and whose elements are all distinct. Return that maximum, or 0 if no subarray meets the conditions.

Example 1:
Input: {"nums":[1,5,4,2,9,9,9],"k":3}
Output: 15
Constraints:
  • 1≤k≤nums.length≤1051 \leq k \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1051 \leq \text{nums}[i] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,5,4,2,9,9,9],"k":3}

Slide a window of exactly 3 values. A hash map counts each value inside it; the window qualifies only when the map has 3 keys, meaning no value repeats.

nums · window size k = 3

1

0

5

1

4

2

2

3

9

4

9

5

9

6

count map: 0 keys for 3 slots

empty

window sum

-

distinct

-

best

0

Variables
VariableValue
k3
best0
DepthFunction Call
Stack empty
0/17