↓Skip to main content
  1. LeetCode/

LeetCode 2841: Maximum Sum of Almost Unique Subarray

·2 mins· ·
LeetCode Medium Sliding-Window Hash-Table Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2025-12-23

  • Submissions: Wrong Answer → Accepted

Approach
#

A fixed window of length k maintains two things:

  • The window sum.
  • A count map cnt: value → occurrences in the window. Delete a key when its count drops to 0, so len(cnt) is the number of distinct values.

When the window is full and len(cnt) >= m, update the best sum.

My Attempts
#

Attempt 1 checked “each value appears <= k - m times”, which is not the same as “at least m distinct values”, and only checked the value just added. For nums = [2], m = 1, k = 1, k - m = 0, so 2 appearing once failed the check and it returned 0; the answer is 2.

Checking len(freq) >= m directly and deleting keys at zero passed.

Solution
#

class Solution:
    def maxSum(self, nums: List[int], m: int, k: int) -> int:
        cnt = Counter()
        window = best = 0
        for right, x in enumerate(nums):
            cnt[x] += 1
            window += x
            if right >= k:
                out = nums[right - k]
                cnt[out] -= 1
                window -= out
                if cnt[out] == 0:
                    del cnt[out]                   # keeps len(cnt) = distinct count
            if right >= k - 1 and len(cnt) >= m:
                best = max(best, window)
        return best

Complexity
#

Time O(n), space O(k).

Mistakes to Avoid
#

  • Inferring the distinct count from occurrence counts: use the map’s size.
  • Not deleting keys at zero: len() over-counts.

Interview Explanation
#

A fixed sliding window of length k keeps the sum and a count map. When an element leaves, its count drops and the key is deleted at zero, so the map’s size is the number of distinct values. When the window is full with at least m distinct values, update the answer. Time O(n).

Related

LeetCode 1248: Count Number of Nice Subarrays
·3 mins
LeetCode Medium Sliding-Window Prefix-Sum Hash-Table Array
LeetCode 1248 note: “exactly k odd numbers” is not monotonic, so compute “at most k” minus “at most k - 1”; or use prefix sums with a hash map
LeetCode 1814: Count Nice Pairs in an Array
·1 min
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 note: rearrange the condition into nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]), count pairs per value, and remember the modulus
LeetCode 3071: Minimum Operations to Write the Letter Y on a Grid
·2 mins
LeetCode Medium Array Hash-Table Matrix Counting
LeetCode 3071 note: count each value on and off the Y, enumerate the Y value a and background value b (a != b), and take the fewest cells to change
LeetCode 187: Repeated DNA Sequences
·1 min
LeetCode Medium Hash-Table String Bit-Manipulation Sliding-Window
LeetCode 187 note: count every length-10 substring in a hash map and return those seen more than once
LeetCode 229: Majority Element II
·2 mins
LeetCode Medium Array Hash-Table Sorting Counting
LeetCode 229 note: at most two values can exceed n / 3; Boyer-Moore keeps two candidates and a second pass verifies their counts
LeetCode 106: Construct Binary Tree from Inorder and Postorder Traversal
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 106 note: the last post-order value is the root; taking roots from the end of the post-order, build the right subtree before the left