DSA problem
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, and - 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.
This combines a fixed-size window of width k with a distinctness check. We slide the window across the array, maintaining both the running sum and a frequency map of the elements currently inside the window. Whenever the window has exactly k elements and every element appears exactly once, the window is a valid candidate.
Examples
nums = [1,5,4,2,9,9,9], k = 315nums = [4,4,4], k = 30nums = [9,9,9,1,2,3], k = 36Constraints
- 1 <= k <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.