Maximum Sum of Distinct Subarrays With Length K

Problem

Find the maximum sum of a subarray of exactly length k whose elements are all distinct. If no such subarray exists, return 0.

Input:  nums = [1,5,4,2,9,9,9], k = 3
Output: 15   ([5,4,2] & later, but max distinct-sum window is 15)

Python Solution

def maximum_subarray_sum(nums, k):
    counts = {}
    window_sum = 0
    best = 0
    for i, num in enumerate(nums):
        counts[num] = counts.get(num, 0) + 1
        window_sum += num
        if i >= k:
            left_num = nums[i - k]
            counts[left_num] -= 1
            window_sum -= left_num
            if counts[left_num] == 0:
                del counts[left_num]
        if i >= k - 1 and len(counts) == k:
            best = max(best, window_sum)
    return best

C++ Solution

long long maximumSubarraySum(vector<int>& nums, int k) {
    unordered_map<int, int> counts;
    long long windowSum = 0, best = 0;
    for (int i = 0; i < nums.size(); i++) {
        counts[nums[i]]++;
        windowSum += nums[i];
        if (i >= k) {
            int leftNum = nums[i - k];
            counts[leftNum]--;
            windowSum -= leftNum;
            if (counts[leftNum] == 0) counts.erase(leftNum);
        }
        if (i >= k - 1 && counts.size() == k) {
            best = max(best, windowSum);
        }
    }
    return best;
}

Java Solution

class Solution {
    public long maximumSubarraySum(int[] nums, int k) {
        Map<Integer, Integer> counts = new HashMap<>();
        long windowSum = 0, best = 0;
        for (int i = 0; i < nums.length; i++) {
            counts.merge(nums[i], 1, Integer::sum);
            windowSum += nums[i];
            if (i >= k) {
                int leftNum = nums[i - k];
                counts.merge(leftNum, -1, Integer::sum);
                windowSum -= leftNum;
                if (counts.get(leftNum) == 0) counts.remove(leftNum);
            }
            if (i >= k - 1 && counts.size() == k) {
                best = Math.max(best, windowSum);
            }
        }
        return best;
    }
}

Complexity

Time: O(n) — each element enters and leaves the fixed-size window exactly once. Space: O(k) — the count map holds at most k entries when the window is full.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.