# 2516. Take K of Each Character From Left and Right
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/description/
## 思路
Instead of taking ```k``` of each character from left and right, we take at most ```count(c)-k``` of each character from middle.
## Code
```python=
class Solution:
def takeCharacters(self, s: str, k: int) -> int:
limits = {c: s.count(c)-k for c in 'abc'}
if any(limit < 0 for limit in limits.values()):
return -1
cnt = Counter()
maxLen = 0
left = 0
for right in range(len(s)):
cnt[s[right]] += 1
while cnt[s[right]]>limits[s[right]]:
cnt[s[left]] -= 1
left += 1
maxLen = max(maxLen, right-left+1)
return len(s)-maxLen
```