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.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int MaximumUniqueSubarray(int[] nums) {
Dictionary<int, int> lastOccurrence = new Dictionary<int, int>();
int left = 0, currentSum = 0, maxScore = 0;
for (int right = 0; right < nums.Length; right++) {
if (lastOccurrence.ContainsKey(nums[right]) && lastOccurrence[nums[right]] >= left) {
left = lastOccurrence[nums[right]] + 1;
}
int newSum = 0;
for (int i = left; i <= right; i++) {
newSum += nums[i];
}
currentSum = newSum;
maxScore = Math.Max(maxScore, currentSum);
lastOccurrence[nums[right]] = right;
}
return maxScore;
}
public static void Main(string[] args) {
Solution sol = new Solution();
int[] nums = new int[] { 4, 2, 4, 5, 6 };
Console.WriteLine(sol.MaximumUniqueSubarray(nums)); // Output: 17
}
}
This C# solution utilizes a Dictionary to manage the last seen indices of elements. The for
loop iterates through the array, adjusting the left
pointer and calculating new sums for unique subarrays efficiently, ensuring maximum value is tracked.