I used a sliding window technique with a set to keep track of the unique elements in the current window using two pointers: left and right. As I moved right through the array, I kept adding elements to a running sum and to the set. If I encountered a duplicate element (i.e., one already in the set), I slid the left pointer forward and removed elements from the set and subtracted their values from the sum until the duplicate was removed. At each step, I updated the maximum sum I could get.
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
seen = set()
left = 0
current_sum = 0
max_sum = 0
for right in range(len(nums)):
while nums[right] in seen:
seen.remove(nums[left])
current_sum -= nums[left]
left += 1
seen.add(nums[right])
current_sum += nums[right]
max_sum = max(max_sum, current_sum)
return max_sum
- Time: O(n)
- Space: O(n)
