#2461

Maximum Sum of Distinct Subarrays With Length K

Medium
ArrayHash TableSliding WindowHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a sliding window approach allows us to efficiently track the current subarray and its distinct elements, updating the sum as we slide the window across the array. This avoids the need to recheck all elements repeatedly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hash map to count occurrences of elements and a variable for the current sum.
  2. 2Step 2: Use a sliding window of size k to traverse the array, adding new elements and removing old ones as the window slides.
  3. 3Step 3: If the window contains all distinct elements, update the maximum sum.
solution.py17 lines
1def maxSumDistinctSubarray(nums, k):
2    count = {}
3    max_sum = 0
4    current_sum = 0
5    n = len(nums)
6    for i in range(n):
7        if i >= k:
8            left = nums[i - k]
9            count[left] -= 1
10            if count[left] == 0:
11                del count[left]
12                current_sum -= left
13        count[nums[i]] = count.get(nums[i], 0) + 1
14        current_sum += nums[i]
15        if len(count) == k:
16            max_sum = max(max_sum, current_sum)
17    return max_sum

Complexity note: The time complexity is O(n) because we traverse the array once, and the space complexity is O(n) due to the hash map storing counts of elements.

  • 1The sliding window technique is useful for problems involving contiguous subarrays.
  • 2Using a hash map allows for efficient tracking of element counts and distinctness.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.