Sponsored
Sponsored
The sliding window technique can be used here to find the maximum sum of a subarray with unique elements. The idea is to maintain a window with unique elements using a HashSet. Start with two pointers, both at the beginning of the array. As you extend the window by moving the right pointer, check if the current element is already in the HashSet:
Time Complexity: O(n), where n is the size of the input array, because each element will be visited at most twice.
Space Complexity: O(min(n, m)), where m is the maximum possible number of unique elements (10,000 in this case).
1def maximum_unique_subarray(nums):
2 unique_elements = set()
3 left, current_sum, max_score = 0, 0, 0
4 for right in range(len(nums)):
5 while nums[right] in unique_elements:
6 unique_elements.remove(nums[left])
7 current_sum -= nums[left]
8 left += 1
9 unique_elements.add(nums[right])
10 current_sum += nums[right]
11 max_score = max(max_score, current_sum)
12 return max_score
13
14# Example usage:
15nums = [4, 2, 4, 5, 6]
16print(maximum_unique_subarray(nums)) # Output: 17
This Python function uses a sliding window approach with a HashSet to track the current subarray of unique elements. Two pointers are maintained: left
and right
. The right
pointer expands the window, and whenever a duplicate is found, the left
pointer moves forward to remove duplicates. This ensures the subarray between left
and right
remains unique, while continually updating the maximum score.
By using a HashMap, it can be optimized to store the last occurrence index of each element. While iterating, if a duplicate is found, directly jump the left pointer to the element's next position after its last occurrence:
Time Complexity: O(n), each element is processed once and the sum of subarrays is managed efficiently.
Space Complexity: O(n) due to the use of a HashMap for last occurrences.
1function maximumUniqueSubarray(nums) {
2
This JavaScript solution uses a HashMap (lastOccurrence
) to keep track of the indices at which elements last appeared. As the right pointer moves, if a duplicate is encountered, the left pointer quickly jumps to one position after the last occurrence of the duplicate, maintaining an efficient window of unique elements.