#2841

Maximum Sum of Almost Unique Subarray

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 maintain the sum and count of distinct elements as we move through the array, avoiding the need to repeatedly calculate sums and distinct counts.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a sliding window of size k, using two pointers to track the start and end.
  2. 2Step 2: Use a HashMap to count occurrences of each element in the current window.
  3. 3Step 3: As you slide the window, update the sum and the count of distinct elements. If the count of distinct elements is at least m, compare and possibly update the maximum sum.
solution.py27 lines
1# Full working Python code
2
3def max_sum_almost_unique(nums, m, k):
4    from collections import defaultdict
5    max_sum = 0
6    current_sum = 0
7    count_map = defaultdict(int)
8    n = len(nums)
9
10    for i in range(n):
11        count_map[nums[i]] += 1
12        current_sum += nums[i]
13
14        if i >= k:
15            count_map[nums[i - k]] -= 1
16            current_sum -= nums[i - k]
17            if count_map[nums[i - k]] == 0:
18                del count_map[nums[i - k]]
19
20        if i >= k - 1:
21            if len(count_map) >= m:
22                max_sum = max(max_sum, current_sum)
23
24    return max_sum
25
26# Example usage
27print(max_sum_almost_unique([2, 6, 7, 3, 1, 7], 3, 4))

Complexity note: The time complexity is O(n) because we traverse the array once while maintaining the sum and distinct counts dynamically. The space complexity is O(n) due to the HashMap storing counts of elements.

  • 1Using a sliding window technique allows for efficient sum and distinct element tracking.
  • 2HashMaps are useful for counting occurrences and managing distinct elements.

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