Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created July 22, 2025 16:37
Show Gist options
  • Save tatsuyax25/34440b0f3abb1fab7d19430c12f622ce to your computer and use it in GitHub Desktop.
Save tatsuyax25/34440b0f3abb1fab7d19430c12f622ce to your computer and use it in GitHub Desktop.
You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one suba
/**
* @param {number[]} nums
* @return {number}
*/
var maximumUniqueSubarray = function(nums) {
let seen = new Set(); // To track unique elements in the current window
let left = 0; // Left boundary of the sliding window
let maxScore = 0; // To Keep track of the maximum score found
let currentSum = 0; // Sum of the current window
for (let right = 0; right < nums.length; right++) {
// If duplicate is found, shrink window from the left
while (seen.has(nums[right])) {
seen.delete(nums[left]); // Remove element from Set
currentSum -= nums[left]; // Subtract its value from the current
left++; // Move window forward
}
// Add new unique element to the window
seen.add(nums[right]);
currentSum += nums[right];
maxScore = Math.max(maxScore, currentSum); // Update max score
}
return maxScore;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment