Untitled

 avatar
unknown
plain_text
a month ago
1.2 kB
1
Indexable
import java.util.HashSet;

public class MaximumErasureScore {
    public static int maximumUniqueSubarray(int[] nums) {
        HashSet<Integer> uniqueElements = new HashSet<>();
        int i = 0, j = 0, currentSum = 0, maxScore = 0;

        // Sliding window using a while loop
        while (j < nums.length) {
            // If the element is already in the window, shrink the window
            while (uniqueElements.contains(nums[j])) {
                uniqueElements.remove(nums[i]);
                currentSum -= nums[i];
                i++; // Move the start pointer
            }

            // Add the current element to the window
            uniqueElements.add(nums[j]);
            currentSum += nums[j];

            // Update the maximum score
            maxScore = Math.max(maxScore, currentSum);

            // Expand the window
            j++;
        }

        return maxScore;
    }

    public static void main(String[] args) {
        System.out.println(maximumUniqueSubarray(new int[]{4, 2, 4, 5, 6})); // Output: 17
        System.out.println(maximumUniqueSubarray(new int[]{5, 2, 1, 2, 5, 2, 1, 2, 5})); // Output: 8
    }
}
Leave a Comment