Maximum Erasure Value (Longest Unique Subarray Sum)

Problem

Find the maximum sum of a contiguous subarray whose elements are all unique.

Input:  nums = [4,2,4,5,6]
Output: 17   ([2,4,5,6])

Python Solution

def maximum_unique_subarray(nums):
    seen = set()
    left = 0
    window_sum = 0
    best = 0
    for right, num in enumerate(nums):
        while num in seen:
            seen.remove(nums[left])
            window_sum -= nums[left]
            left += 1
        seen.add(num)
        window_sum += num
        best = max(best, window_sum)
    return best

C++ Solution

int maximumUniqueSubarray(vector<int>& nums) {
    unordered_set<int> seen;
    int left = 0, windowSum = 0, best = 0;
    for (int right = 0; right < nums.size(); right++) {
        while (seen.count(nums[right])) {
            seen.erase(nums[left]);
            windowSum -= nums[left];
            left++;
        }
        seen.insert(nums[right]);
        windowSum += nums[right];
        best = max(best, windowSum);
    }
    return best;
}

Java Solution

class Solution {
    public int maximumUniqueSubarray(int[] nums) {
        Set<Integer> seen = new HashSet<>();
        int left = 0, windowSum = 0, best = 0;
        for (int right = 0; right < nums.length; right++) {
            while (seen.contains(nums[right])) {
                seen.remove(nums[left]);
                windowSum -= nums[left];
                left++;
            }
            seen.add(nums[right]);
            windowSum += nums[right];
            best = Math.max(best, windowSum);
        }
        return best;
    }
}

Complexity

Time: O(n) — the left pointer only moves forward, so total shrink operations are bounded by n. Space: O(n) for the set in the worst case, when all elements are unique.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.