From ae38168d439859c9038f8dc496fd8fe034a356c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Khoa=20Hu=E1=BB=B3nh=20=28Daniel=29?= Date: Sat, 30 Mar 2024 23:34:25 +0700 Subject: [PATCH] Create main.go --- solution/992/main.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 solution/992/main.go diff --git a/solution/992/main.go b/solution/992/main.go new file mode 100644 index 0000000..c13b334 --- /dev/null +++ b/solution/992/main.go @@ -0,0 +1,28 @@ +package main +func subarraysWithKDistinct(nums []int, k int) int { + return atMostKDistinct(nums, k) - atMostKDistinct(nums, k-1) +} + +func atMostKDistinct(nums []int, k int) int { + myMap := make(map[int]int) + left, count, result := 0, 0, 0 + + for right, num := range nums { + if myMap[num] == 0 { + count++ + } + myMap[num]++ + + for count > k { + myMap[nums[left]]-- + if myMap[nums[left]] == 0 { + count-- + } + left++ + } + + result += right - left + 1 + } + + return result +}