Statement
Given an integer array nums and an integer k, consider every contiguous subarray of nums whose length is exactly k. A subarray is valid if all of its elements are distinct. Return the maximum possible sum among all valid subarrays. If no valid subarray exists, return 0.
Constraints:
Examples
Sample Example 1
Input: nums = [1, 5, 4, 2, 9, 9, 9]-List[int], k = 3-int
Output: 15-int
Explanation: Valid length-3 subarrays with all distinct elements include [1,5,4] (sum 10), [5,4,2] (sum 11), and [4,2,9] (sum 15). Subarrays like [2,9,9] are invalid due to duplicates, so the maximum valid sum is 15.
Sample Example 2
Input: nums = [4, 4, 4]-List[int], k = 2-int
Output: 0-int
Explanation: Every length-2 subarray is [4,4], which contains duplicates, so no valid subarray exists and the answer is 0.
Sample Example 3
Input: nums = [10, 2, 3, 4, 5]-List[int], k = 5-int
Output: 24-int
Explanation: The only length-5 subarray is the entire array. All elements are distinct, so the sum 10+2+3+4+5 = 24 is returned.
Sample Example 4
Input: nums = [1, 2, 1, 3, 4]-List[int], k = 3-int
Output: 8-int
Explanation: The length-3 subarrays are [1,2,1] (invalid, duplicate 1), [2,1,3] (valid, sum 6), and [1,3,4] (valid, sum 8), so the maximum valid sum is 8.
Sample Example 5
Input: nums = [5, 1, 5, 2, 3, 2]-List[int], k = 2-int
Output: 7-int
Explanation: Valid length-2 subarrays include [5,1] (sum 6), [1,5] (sum 6), [5,2] (sum 7), [2,3] (sum 5), and [3,2] (sum 5), so the maximum is 7 from [5,2].
Understand the problem
Now, let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem: