Problem Description
Given an array of positive integers nums, find exactly one contiguous subarray that contains only unique elements such that the sum of this subarray is maximized. The answer is the maximum sum obtainable from any such unique-element subarray.
Key Insights
- Use a sliding window to maintain a subarray with unique elements.
- A set or hash map is used to efficiently track and check for duplicates.
- Expand the window while elements are unique, and contract it when a duplicate is encountered.
- Maintain a running sum for the current window and update the maximum sum when applicable.
Space and Time Complexity
Time Complexity: O(n) – each element is processed once. Space Complexity: O(n) – additional space is used for the set/hash map in the worst case.
Solution
We solve the problem using the sliding window technique. Two pointers (left and right) define the current window of unique elements. As we iterate over the array with the right pointer, we add the current element to the running sum and the set. If a duplicate is encountered, we move the left pointer forward until the duplicate is removed from the set, deducting the removed elements from the running sum. At each step, we update the maximum sum if the current sum is higher than the previously computed maximum. This approach efficiently finds the maximum sum of a contiguous subarray with unique elements.