LeetCode 1695: Maximum Erasure Value Solution

Master LeetCode problem 1695 (Maximum Erasure Value), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1695. Maximum Erasure Value

Problem Explanation

Explanation:

To solve this problem, we can use a sliding window approach. We will maintain a set to keep track of unique elements in the current window. Initially, we will start with an empty set and two pointers left and right to define the window.

  1. Move the right pointer to the right until we encounter a duplicate element. During this process, update the sum of elements in the window and store the maximum sum encountered so far.
  2. When a duplicate element is encountered, move the left pointer to the right until the duplicate element is removed from the window (i.e., the window contains only unique elements).
  3. Repeat steps 1 and 2 until the right pointer reaches the end of the array.

The maximum of all the sums encountered during this process will be the answer.

Time Complexity: O(n), where n is the number of elements in the input array. Space Complexity: O(n) for the set to store unique elements in the window.

:

Solution Code

class Solution {
    public int maximumUniqueSubarray(int[] nums) {
        Set<Integer> set = new HashSet<>();
        int left = 0, right = 0, sum = 0, maxSum = 0;
        
        while (right < nums.length) {
            if (set.add(nums[right])) {
                sum += nums[right];
                maxSum = Math.max(maxSum, sum);
                right++;
            } else {
                sum -= nums[left];
                set.remove(nums[left]);
                left++;
            }
        }
        
        return maxSum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1695 (Maximum Erasure Value)?

This page provides optimized solutions for LeetCode problem 1695 (Maximum Erasure Value) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1695 (Maximum Erasure Value)?

The time complexity for LeetCode 1695 (Maximum Erasure Value) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1695 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1695 in Java, C++, or Python.

Back to LeetCode Solutions