Skip to content
Decoder

Maximum Sum of Distinct Subarrays With Length K

Medium

Problem

Given an array nums and an integer k, consider every subarray of length `k` whose elements are all distinct. Return the largest sum among them, or 0 if no such subarray exists.

Example 1

Input
nums = [1, 5, 4, 2, 9, 9, 9], k = 3
Output
15
Why
[5, 4, 2] = 11, [4, 2, 9] = 15

Example 2

Input
nums = [4, 4, 4], k = 3
Output
0

Constraints

  • 1 <= k <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.