Skip to content

Commit 2c3e3f1

Browse files
Merge pull request #190
add new hard problem sliding window 8.05
2 parents d69191f + b9762b1 commit 2c3e3f1

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowLeetcode.kt

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,3 +205,35 @@ fun minSubArrayLen(target: Int, nums: IntArray): Int {
205205
else -> minLen
206206
}
207207
}
208+
209+
/**
210+
* 992. Subarrays with K Different Integers
211+
*/
212+
213+
fun subArraysWithKDistinct(nums: IntArray, k: Int): Int {
214+
return atMostK(nums, k) - atMostK(nums, k - 1)
215+
}
216+
217+
private fun atMostK(nums: IntArray, k: Int): Int {
218+
var count = 0
219+
val freq = mutableMapOf<Int, Int>()
220+
var left = 0
221+
222+
for (right in nums.indices) {
223+
val num = nums[right]
224+
freq[num] = freq.getOrDefault(num, 0) + 1
225+
226+
while (freq.size > k) {
227+
val leftNum = nums[left]
228+
freq[leftNum] = freq[leftNum]!! - 1
229+
if (freq[leftNum] == 0) {
230+
freq.remove(leftNum)
231+
}
232+
left++
233+
}
234+
235+
count += right - left + 1
236+
}
237+
238+
return count
239+
}

0 commit comments

Comments
 (0)