Question bank › Sliding Window
Dsa Sliding Window Hard

Max Subarray Sum with K Distinct Elements

Given an array of integers and a positive integer `k`, find the maximum sum of a contiguous subarray that contains exactly `k` distinct integers. If no such subarray exists, return 0. Input: - The first line contains two integers `n` (the number of elements in the array) and `k` (the number of distinct integers). - The second line contains `n` integers, the elements of the array. Output: - A single integer, representing the maximum sum of the subarray fulfilling the criteria. Example: Input: 5 2 1 2 1 2 3 Output: 5 In this example, the subarray [1, 2, 1, 2] has a sum of 5 and contains exactly 2 distinct integers.

Key concepts

sliding_windowhashmapsubarray

Practise this out loud — free

Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.

🎙 Practise this question now
Part of InterviewLab's verified interview question bank. We show the prompt and concepts to practise with — never a copy-paste solution.