[LeetCode] Minimum Subarray Length With Distinct Sum At Least K

3795. Minimum Subarray Length With Distinct Sum At Least K

You are given an integer array nums and an integer k.

Return the minimum length of a subarray whose sum of the distinct values present in that subarray (each value counted once) is at least k. If no such subarray exists, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int minLength(vector<int>& nums, int k) {
unordered_map<int,int> freq;
int sum = 0, res = INT_MAX;
auto append = [&](int x) {
if(freq[x] == 0) sum += x;
++freq[x];
};
auto pop = [&](int x) {
if(freq[x] == 1) sum -= x;
--freq[x];
};
for(int i = 0, j = 0; i < nums.size(); i++) {
while(j < nums.size() and sum < k) append(nums[j++]);
if(sum >= k) {
res = min(res, j - i);
}
pop(nums[i]);
}

return res == INT_MAX ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-subarray-length-with-distinct-sum-at-least-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.