---
# System prepended metadata

title: LC 2516. Take K of Each Character From Left and Right
tags: [medium, leedcode, Sliding Window, c++]

---

# LC 2516. Take K of Each Character From Left and Right

### [Problem link](https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/)

###### tags: `leedcode` `medium` `c++` `Sliding Window`

You are given a string <code>s</code> consisting of the characters <code>'a'</code>, <code>'b'</code>, and <code>'c'</code> and a non-negative integer <code>k</code>. Each minute, you may take either the  **leftmost**  character of <code>s</code>, or the  **rightmost**  character of <code>s</code>.

Return the  **minimum**  number of minutes needed for you to take  **at least**  <code>k</code> of each character, or return <code>-1</code> if it is not possible to take <code>k</code> of each character.

**Example 1:** 

```
Input: s = "aabaaaacaabc", k = 2
Output: 8
Explanation: 
Take three characters from the left of s. You now have two 'a' characters, and one 'b' character.
Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.
A total of 3 + 5 = 8 minutes is needed.
It can be proven that 8 is the minimum number of minutes needed.
```

**Example 2:** 

```
Input: s = "a", k = 1
Output: -1
Explanation: It is not possible to take one 'b' or 'c' so return -1.
```

 **Constraints:** 

- <code>1 <= s.length <= 10<sup>5</sup></code>
- <code>s</code> consists of only the letters <code>'a'</code>, <code>'b'</code>, and <code>'c'</code>.
- <code>0 <= k <= s.length</code>

## Solution 1 - Sliding Window
#### C++
```cpp=
class Solution {
public:
    bool isValid(vector<int>& cnt, int k) {
        for (int& n: cnt) {
            if (n < k) {
                return false;
            }
        }
        return true;
    }

    int takeCharacters(string s, int k) {
        vector<int> cnt(3, 0);
        for (char& c: s) {
            cnt[c - 'a']++;
        }

        int longest = -1;
        int l = 0;
        for (int r = 0; r < s.size(); r++) {
            cnt[s[r] - 'a']--;
            while (l <= r && isValid(cnt, k) == false) {
                cnt[s[l] - 'a']++;
                l++;
            }
            if (isValid(cnt, k) == true) {
                longest = max(longest, r - l + 1);
            }
        }
        return longest == -1 ? -1 : s.size() - longest;
    }
};
```

>### Complexity
>n = s.length
>|             | Time Complexity | Space Complexity |
>| ----------- | --------------- | ---------------- |
>| Solution 1  | O(n)            | O(1)             |

## Note
Sol1:
正難則反: 反向思考如何取得最長的subarray讓剩下abc的個數都 >= k
