Loading problems...
TL;DR: Use a sliding window to maintain a contiguous segment of unique elements, dynamically shrinking the window from the left when duplicates occur or the length exceeds , while tracking the running sum.
You are given an integer array nums and an integer k. The goal of LeetCode 2461 is to identify a contiguous subarray of exactly length k where every element is unique (distinct). Among all such valid subarrays, you must return the maximum possible sum. If no subarray satisfies these conditions, the function should return 0.
This problem, "Maximum Sum of Distinct Subarrays With Length K", combines constraints on window size with constraints on element uniqueness, requiring an efficient traversal method to avoid redundant calculations.
The naive approach involves checking every possible subarray of length to see if it meets the distinctness requirement and then calculating its sum.
ki from 0 to n - k.i, consider the subarray from i to i + k - 1.k (implying all elements are unique), calculate the sum of the subarray.python# Pseudo-code for Brute Force def maximumSubarraySum(nums, k): max_sum = 0 for i in range(len(nums) - k + 1): subarray = nums[i : i + k] if len(set(subarray)) == k: # Check distinct current_sum = sum(subarray) max_sum = max(max_sum, current_sum) return max_sum
Why this fails:
The time complexity of this approach is . The constraints state that nums.length (N) can be up to and k can also be up to . In the worst case, this results in approximately operations, which will inevitably trigger a Time Limit Exceeded (TLE) error. We need an solution.
The core inefficiency in the brute force method is the repetitive work: re-checking uniqueness and re-calculating the sum for overlapping parts of the subarrays.
The Sliding Window pattern optimizes this by maintaining a "running state" as we traverse the array.
current_sum and a frequency map (or set) of elements currently inside the window [left, right].nums[right] creates a duplicate, the window is invalid regardless of its size. We must shrink the window from the left until the duplicate is removed. This ensures the window always contains distinct elements.k, we simply shrink from the left to maintain the size constraint.k and we have ensured distinctness (via step 2), we consider current_sum for the answer.Visual Description:
Imagine a window expanding to the right. As nums[right] enters, we check if it already exists in our window. If it does, the left pointer advances, dropping elements and reducing the sum, until the previous instance of nums[right] is ejected. Only then is the new element valid. Once the window stabilizes with distinct elements, if its width is k, we record the sum.

Let's trace nums = [1, 5, 4, 2, 9, 9, 9], k = 3.
left=0, right=0. Window: [1]. Sum: 1. Size: 1.right=1. Window: [1, 5]. Sum: 6. Size: 2.right=2. Window: [1, 5, 4]. Sum: 10. Size: 3. Valid (Size=k). max_sum = 10.right=3. Window: [1, 5, 4, 2]. Size 4 > k.
[5, 4, 2]. Sum: 11. Size: 3. Valid. max_sum = 11.right=4. Window: [5, 4, 2, 9]. Size 4 > k.
[4, 2, 9]. Sum: 15. Size: 3. Valid. max_sum = 15.right=5. Element is 9. 9 is already in Set!
[2, 9]. 9 still in set.[9]. 9 still in set.[]. 9 gone.[9]. Sum: 9. Size: 1.right=6. Element is 9. 9 is already in Set!
[].[9]. Sum: 9. Size: 1.The algorithm is correct because it maintains an invariant: the window nums[left...right] always contains distinct elements after the inner while loop executes.
right).right, left is adjusted to the minimum index such that nums[left...right] is valid (distinct and length ).k, and the window slides continuously covering all valid ranges, we are guaranteed to find the maximum sum.cpp#include <vector> #include <unordered_set> #include <algorithm> using namespace std; class Solution { public: long long maximumSubarraySum(vector<int>& nums, int k) { long long maxSum = 0; long long currentSum = 0; unordered_set<int> seen; int left = 0; for (int right = 0; right < nums.size(); ++right) { // If duplicate exists, shrink window from left until duplicate is removed while (seen.count(nums[right])) { currentSum -= nums[left]; seen.erase(nums[left]); left++; } // Add current element currentSum += nums[right]; seen.insert(nums[right]); // If window size exceeds k, shrink from left if (right - left + 1 > k) { currentSum -= nums[left]; seen.erase(nums[left]); left++; } // If window size is exactly k, update max sum if (right - left + 1 == k) { maxSum = max(maxSum, currentSum); } } return maxSum; } };
javaimport java.util.HashSet; import java.util.Set; class Solution { public long maximumSubarraySum(int[] nums, int k) { long maxSum = 0; long currentSum = 0; Set<Integer> seen = new HashSet<>(); int left = 0; for (int right = 0; right < nums.length; right++) { // If duplicate exists, shrink window from left while (seen.contains(nums[right])) { currentSum -= nums[left]; seen.remove(nums[left]); left++; } // Add current element seen.add(nums[right]); currentSum += nums[right]; // If window size exceeds k, shrink from left if (seen.size() > k) { currentSum -= nums[left]; seen.remove(nums[left]); left++; } // If window size is exactly k, update max sum if (seen.size() == k) { maxSum = Math.max(maxSum, currentSum); } } return maxSum; } }
pythonclass Solution: def maximumSubarraySum(self, nums: List[int], k: int) -> int: max_sum = 0 current_sum = 0 seen = set() left = 0 for right in range(len(nums)): # While duplicate exists, shrink from left while nums[right] in seen: current_sum -= nums[left] seen.remove(nums[left]) left += 1 # Add current element seen.add(nums[right]) current_sum += nums[right] # If window size exceeds k, shrink from left if len(seen) > k: current_sum -= nums[left] seen.remove(nums[left]) left += 1 # If window size is exactly k, update result if len(seen) == k: max_sum = max(max_sum, current_sum) return max_sum
left and right pointers traverse the array at most once. Each element is added to the Set/Sum once and removed at most once. Operations on the Set (add, remove, contains) are on average. Thus, the total time is linear relative to the input size.The Sliding Window - Variable Size (Condition-Based) pattern is a fundamental technique for array and string problems. Mastering it here helps with:
In all these cases, the left and right pointers move unidirectionally to satisfy a specific invariant efficiently.
Q: Why did I get a Time Limit Exceeded (TLE)?
sum(nums[i:i+k]) or recreating the Set from scratch in every iteration.currentSum incrementally ().Q: Why is my output returning 0 when there are valid subarrays?
max_sum to a very small negative number (though sums here are positive, logic errors in initialization are common).max_sum never updates.Q: Why does my logic fail on duplicates?
nums[right] == nums[right-1] for duplicates.[4, 1, 2, 4]), not just adjacent to the current element.