2024-11-20 Daily Challenge
Today I have done leetcode's November LeetCoding Challenge with cpp
.
November LeetCoding Challenge 20
Description
Take K of Each Character From Left and Right
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
Solution
class Solution {
public:
int takeCharacters(string s, int k) {
int count[3] = {};
auto check = [&](){ return count[0] >= k && count[1] >= k && count[2] >= k; };
int left;
for(left = 0; left < s.length() && !check(); ++left) {
count[s[left] - 'a'] += 1;
}
if(!check()) return -1;
int answer = left;
for(int right = s.length() - 1; right >= 0; --right) {
count[s[right] - 'a'] += 1;
while(check() && left > 0) {
answer = min<int>(answer, left + s.length() - right);
count[s[left - 1] - 'a'] -= 1;
left -= 1;
}
if(left == 0 && check()) {
answer = min<int>(answer, s.length() - right);
break;
}
}
return answer;
}
};