3795. Minimum Subarray Length With Distinct Sum At Least K
Description
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.
Β
Example 1:
Input: nums = [2,2,3,1], k = 4
Output: 2
Explanation:
The subarray [2, 3] has distinct elements {2, 3} whose sum is 2 + 3 = 5, which is βββββββat least k = 4. Thus, the answer is 2.
Example 2:
Input: nums = [3,2,3,4], k = 5
Output: 2
Explanation:
The subarray [3, 2] has distinct elements {3, 2} whose sum is 3 + 2 = 5, which is βββββββat least k = 5. Thus, the answer is 2.
Example 3:
Input: nums = [5,5,4], k = 5
Output: 1
Explanation:
The subarray [5] has distinct elements {5} whose sum is 5, which is at least k = 5. Thus, the answer is 1.
Β
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1051 <= k <= 109
Solutions
Solution 1: Sliding Window
We use a hash table \(\textit{cnt}\) to record the occurrence count of each element in the current window, and a variable \(\textit{s}\) to record the sum of distinct elements in the current window. We use two pointers \(l\) and \(r\) to represent the left and right boundaries of the current window, both initially pointing to the beginning of the array. We initialize a variable \(\textit{ans}\) to record the minimum length of a window that satisfies the condition, with an initial value of \(n + 1\), where \(n\) is the length of the array.
We continuously move the right pointer \(r\), adding new elements into the window and updating \(\textit{cnt}\) and \(\textit{s}\). When \(\textit{s}\) is greater than or equal to \(k\), we try to move the left pointer \(l\) to shrink the window, updating \(\textit{cnt}\) and \(\textit{s}\) accordingly, until \(\textit{s}\) is less than \(k\). During this process, we record the minimum length of windows that satisfy the condition.
Finally, if \(\textit{ans} \gt n\), it means no valid window exists, and we return \(-1\); otherwise we return \(\textit{ans}\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |