Maximize a Fixed-Length Window Sum with No Repeated Values

Quick Overview

Find the greatest sum of a length-k contiguous subarray containing only distinct values, or return zero when none exists.

Maximize a Fixed-Length Window Sum with No Repeated Values

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Among contiguous subarrays of `nums` with length exactly `k` and no repeated value, return the greatest sum. Return zero if no subarray satisfies both requirements. ```cpp class Solution { public: long long maximumSubarraySum(vector<int>& nums, int k); }; ``` ### Examples **Example 1:** ```text Input: nums = [4,1,3,3,2], k = 3 Output: 8 Explanation: The first window [4,1,3] is distinct; the other two windows repeat3. ``` **Example 2:** ```text Input: nums = [2,2], k = 2 Output: 0 Explanation: The only length-two window has a repeated value. ``` ### Constraints - `1 <= k <= nums.length <= 100000`. - `1 <= nums[i] <= 100000`. ### Clarifying Questions - Must the length be exactly `k`? Yes. - Are repeated values elsewhere in the array forbidden? No; only repetition within the selected subarray matters. - Can `k = 1`? Yes; every single value then qualifies. - What is returned if no window qualifies? Zero. ```hint Check the boundary Check whether a high-sum window repeats a value before comparing it with valid windows. ```

Overview: Find the greatest sum of a length-k contiguous subarray containing only distinct values, or return zero when none exists.

Google logo
Google
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Among contiguous subarrays of nums with length exactly k and no repeated value, return the greatest sum. Return zero if no subarray satisfies both requirements.

class Solution {
public:
    long long maximumSubarraySum(vector<int>& nums, int k);
};

Examples

Example 1:

Input: nums = [4,1,3,3,2], k = 3
Output: 8
Explanation: The first window [4,1,3] is distinct; the other two windows repeat3.

Example 2:

Input: nums = [2,2], k = 2
Output: 0
Explanation: The only length-two window has a repeated value.

Constraints

  • 1 <= k <= nums.length <= 100000 .
  • 1 <= nums[i] <= 100000 .

Clarifying Questions Guidance

  • Must the length be exactly k ? Yes.
  • Are repeated values elsewhere in the array forbidden? No; only repetition within the selected subarray matters.
  • Can k = 1 ? Yes; every single value then qualifies.
  • What is returned if no window qualifies? Zero.