Find the maximum sum of any length- subarray whose elements are all distinct.
Problem
Given an integer array nums and an integer k, consider every contiguous subarray of length k.
Return the maximum possible sum of a subarray of length k such that all elements in that subarray are pairwise distinct.
If no such subarray exists, return 0.
Notes
- A subarray must be contiguous.
- "Distinct" means no value appears more than once inside the chosen window.
Intuition target
The main challenge is to efficiently keep track of both the current window sum and whether the window contains duplicates while scanning the array.
Input Format
nums: an integer arrayk: the required subarray length
You should process all contiguous subarrays of length k.
Output Format
Return a single integer: the maximum sum among all length-k subarrays with all distinct elements, or 0 if none exist.
Constraints
1 <= k <= nums.lengthnums.lengthis at least 1- Values in
numscan be positive, zero, or negative - Use a linear or near-linear approach for best performance
Example 1
Input
nums = [1,5,4,2,9,9,9], k = 3
Output
15
Explanation
The length-3 distinct subarrays are [1,5,4] with sum 10, [5,4,2] with sum 11, and [4,2,9] with sum 15. The maximum is 15.
Example 2
Input
nums = [4,4,4], k = 3
Output
0
Explanation
The only length-3 subarray is [4,4,4], but it is not distinct, so no valid subarray exists.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.