← All problems

2516. Take K of Each Character from Left and Right

MediumOpen on LeetCodeProblem statement

Problem Statement

2516. Take K of Each Character From Left and Right

Medium


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:

Java

Source file
class Solution {
    int minMins = Integer.MAX_VALUE;

    public int takeCharacters(String s, int k) {
        int n = s.length();
        if (k == 0)
            return 0;
        int[] freq = new int[3];
        solve(s, n, k, 0, n - 1, freq);
        return minMins == Integer.MAX_VALUE ? -1 : minMins;
    }

    private void solve(String s, int n, int k, int lt, int rt, int[] freq) {
        if (freq[0] >= k && freq[1] >= k && freq[2] >= k) {
            minMins = Math.min(minMins, n - (rt - lt + 1));
            return;
        }
        if (lt < 0 || rt >= n || lt > rt || n - (rt - lt + 1) >= minMins)
            return;
        freq[s.charAt(lt) - 'a']++;
        solve(s, n, k, lt + 1, rt, freq);
        freq[s.charAt(lt) - 'a']--;
        freq[s.charAt(rt) - 'a']++;
        solve(s, n, k, lt, rt - 1, freq);
        freq[s.charAt(rt) - 'a']--;
    }

}