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

Return _the **minimum** number of minutes needed for you to take **at least**_ `k` _of each character, or return_ `-1` _if it is not possible to take_ `k` _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:**

*   `1 <= s.length <= 105`
*   `s` consists of only the letters `'a'`, `'b'`, and `'c'`.
*   `0 <= k <= s.length`


def min_minutes(s: str, k: int) -> int:
    n = len(s)
    left_counts = [0] * 3
    right_counts = [0] * 3
    for c in s:
        right_counts[ord(c) - ord('a')] += 1

    ans, total = n, 0
    l, r = 0, n - 1
    while l < r:
        while l < r and left_counts[ord(s[l]) - ord('a')] < k and right_counts[ord(s[r]) - ord('a')] < k:
            need_left = max(0, k - left_counts[ord(s[l]) - ord('a')])
            need_right = max(0, k - right_counts[ord(s[r]) - ord('a')])
            if need_left <= need_right:
                total += need_left
                l += 1
                left_counts[ord(s[l]) - ord('a')] += 1
                right_counts[ord(s[l]) - ord('a')] -= 1
            else:
                total += need_right
                r -= 1
                right_counts[ord(s[r]) - ord('a')] -= 1
                left_counts[ord(s[r]) - ord('a')] += 1
        ans = min(ans, total)
        if l + 1 < n:
            total -= left_counts[ord(s[l]) - ord('a')]
            left_counts[ord(s[l]) - ord('a')] -= 1
            right_counts[ord(s[l + 1]) - ord('a')] += 1
            l += 1
        else:
            break
    if all(cnt >= k for cnt in left_counts):
        return ans
    return -1
