------
## 最终结论
```python
def subarraysWithKDistinct(A, K):
    from collections import defaultdict

    def atMostK(k):
        count = defaultdict(int)
        res = left = 0
        for right in range(len(A)):
            if count[A[right]] == 0:
                k -= 1
            count[A[right]] += 1
            
            while k < 0:
                count[A[left]] -= 1
                if count[A[left]] == 0:
                    k += 1
                left += 1
            
            res += right - left + 1
        
        return res

    return atMostK(K) - atMostK(K - 1)

# Example usage:
print(subarraysWithKDistinct([1,2,1,2,3], 2)) # Output: 7
print(subarraysWithKDistinct([1,2,1,3,4], 3)) # Output: 3
```