Find the maximum sum of any length- subarray whose elements are all distinct.
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.
The main challenge is to efficiently keep track of both the current window sum and whether the window contains duplicates while scanning the array.
nums: an integer arrayk: the required subarray lengthYou should process all contiguous subarrays of length k.
Return a single integer: the maximum sum among all length-k subarrays with all distinct elements, or 0 if none exist.
1 <= k <= nums.lengthnums.length is at least 1nums can be positive, zero, or negativeExample 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
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.