Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
We need a contiguous window with no repeated value. Adding a new rightmost value can duplicate only that value, so advancing the left edge until its earlier occurrence is removed restores uniqueness. Since all values are positive, the longest valid window ending at a position also has its greatest sum.
Approach
Track window frequencies, its sum, and a left pointer. Add each new value to the sum and map. While that value occurs twice, remove values from the left, updating both counts and sum. Compare the resulting unique-window sum with the best. Return the maximum over all right endpoints. Zero-frequency map entries may remain stored without affecting the duplicate test.
class Solution:
def maximumUniqueSubarray(self, nums: List[int]) -> int:
n = len(nums)
map = defaultdict(int)
total = 0
res = 0
l = 0
for r in range(n):
map[nums[r]] += 1
total += nums[r]
while l < r and map[nums[r]] == 2:
map[nums[l]] -= 1
total -= nums[l]
l += 1
res = max(res, total)
return resComplexity analysis
Let n = nums.length and u be the number of distinct values tracked. Time: O(n), because each pointer advances at most n times. Auxiliary space: O(u) for the frequency map.
