Problem 1695

Abstract / Summary

Given a string of digits, find the highest sum of unique digit values from any non overlapping substrings.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1695.py

class Solution:
    def maximumUniqueSubarray(self, nums: List[int]) -> int:
        result = 0

        left = 0
        have = set()
        current = 0 # equals sum(have), just a speed trick
        for right in range(len(nums)):
            n = nums[right]
            while n in have:
                have.discard(nums[left])
                current -= nums[left]
                left    += 1

            have.add(n)
            current += n
            result = max(result, current)

        return result
19 lines | 532 bytes | submitted December 8, 2023 | GitHub   6% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The maximumUniqueSubarray method computes the greatest possible sum of a contiguous sub-array that contains no repeated values. It walks through the input list once, maintaining a sliding window that always satisfies the uniqueness constraint. As the window expands and contracts, the algorithm keeps track of the current window sum and records the highest sum observed.

Initialization

At the start, several variables are prepared:

result = 0
left = 0
have = set()
current = 0  # running sum of the elements inside the window

result stores the best sum found so far. left marks the beginning of the sliding window. have is a set that records which numbers are currently inside the window, enabling constant-time membership checks. current mirrors the sum of the elements in have, avoiding the need to recompute the sum from the set on each iteration.

Sliding Window Expansion

The main loop iterates over the right boundary of the window:

for right in range(len(nums)):
    n = nums[right]

right moves from the first to the last index, and n holds the candidate element to be added to the window.

Duplicate Resolution

If the incoming element already exists in the window, the left side of the window is shifted rightward until the duplicate is removed. This guarantees that the window always contains distinct values.

while n in have:
    have.discard(nums[left])
    current -= nums[left]
    left += 1

The while loop repeatedly discards the element at the left index from have, subtracts its value from current, and advances left. The use of discard ensures that the operation is safe even if the element were somehow absent, and the subtraction updates the running sum in constant time.

Incorporating the New Element

Once the duplicate has been eliminated, the new element is added to the window, the running sum is updated, and the best result is possibly refreshed.

have.add(n)
current += n
result = max(result, current)

Adding n to have restores the uniqueness invariant. Updating current reflects the new window sum, and result captures the maximum sum encountered.

Return Value

After the loop finishes, the method returns the highest sum recorded:

return result

Edge Cases Handled

The algorithm gracefully deals with several boundary conditions:

  • Empty input - When nums is empty, the loop body never executes, leaving result at its initial value of 0, which is the correct maximum sum for an empty sub-array.
  • All elements identical - The window never grows beyond a single element because each new element triggers the duplicate-resolution loop, shrinking the window back to size one. The result ends up being the largest single element value.
  • All elements distinct - The while condition never activates, allowing the window to expand to cover the entire list. The final result becomes the sum of the whole array.
  • Negative numbers - The algorithm does not rely on positivity; it still maintains uniqueness and updates the sum accordingly. If the best sub-array consists of a single negative number, result will reflect that value.
  • Large integer values - Since the sum is accumulated incrementally in current, the method can handle very large numbers without overflow concerns in Python’s arbitrary-precision integer arithmetic.

Performance Optimizations

Several deliberate choices improve execution speed:

  • Set for membership testing - Using a hash set (have) provides average-case O(1) checks for the presence of a value, enabling rapid detection of duplicates.
  • Running sum (current) - Maintaining the window sum as a separate variable avoids recomputing the sum of the set on each iteration, which would be linear in the window size.
  • discard instead of remove - discard does not raise an exception if the element is missing, eliminating the need for an explicit existence check before removal.
  • Single pass - The left and right pointers each move forward at most len(nums) steps, ensuring that the total work performed is proportional to the length of the input list.

These techniques together yield an implementation that processes the input efficiently while preserving clarity.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of colorful building blocks laid out on the floor. The goal is to pick up a line of these blocks, one after another, but there is a special rule. Every block held in your hand must be a different color. No two blocks can look the same.

Think of the blocks as numbers in a list. Two markers, named left and right, move along the row to keep track of which blocks are currently in the hand. The right marker walks forward, picking up a new block one by one. If a new block is a color already held, the left marker quickly puts a block back on the floor from the start of the current hand. This happens over and over until the block can be picked up safely without any repeats.

As each new block is added to the hand, the total value of all the held blocks is added up. Whenever a new block makes the group larger than a previous group, a note is made to remember that this new stack is the best one found so far. The process continues until the right marker reaches the very end of the row, having checked every possible group that follows the special rule. The final answer is the memory of the biggest stack that was ever held during the whole walk.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.30 | σ = 0.76

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
31 links | 18 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   December 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality