Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sets
Amazon
Maximum Sum Of Distinct Subarrays With Length K

Find the maximum sum of any length-kk subarray whose elements are all distinct.

Acceptance 0%
Problem Statement

Problem

Given an integer array nums and an integer k, consider every contiguous subarray of length k.

Return the maximum possible sum of a subarray of length k such that all elements in that subarray are pairwise distinct.

If no such subarray exists, return 0.

Notes

  • A subarray must be contiguous.
  • "Distinct" means no value appears more than once inside the chosen window.

Intuition target

The main challenge is to efficiently keep track of both the current window sum and whether the window contains duplicates while scanning the array.

Input Format

  • nums: an integer array
  • k: the required subarray length

You should process all contiguous subarrays of length k.

Output Format

Return a single integer: the maximum sum among all length-k subarrays with all distinct elements, or 0 if none exist.

Constraints

  • 1 <= k <= nums.length
  • nums.length is at least 1
  • Values in nums can be positive, zero, or negative
  • Use a linear or near-linear approach for best performance
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,5,4,2,9,9,9], k = 3

Output

15

Explanation

The length-3 distinct subarrays are [1,5,4] with sum 10, [5,4,2] with sum 11, and [4,2,9] with sum 15. The maximum is 15.

Example 2

Input

nums = [4,4,4], k = 3

Output

0

Explanation

The only length-3 subarray is [4,4,4], but it is not distinct, so no valid subarray exists.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.