#2516

Take K of Each Character From Left and Right

specialist · 855 · lc medium +31 · verified · 51.5% accepted · 1,522 likes · top 41%

Description

Given a string s consisting only of 'a', 'b', and 'c', and a non-negative integer k, each minute you may remove either the leftmost or rightmost character of s. Return the minimum number of minutes needed to collect at least k of each character, or -1 if it is impossible.

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.

Code

1
2
3