LeetCode 2516: Take K of Each Character From Left and Right
Problem Description
Explanation:
To solve this problem, we can use a sliding window approach. We will maintain a window that contains at least k
occurrences of each character. We will expand the window by moving the right pointer to the right until we have at least k
occurrences of each character in the window. Then, we will contract the window by moving the left pointer to the right until we no longer have k
occurrences of each character in the window.
We will keep track of the minimum number of minutes needed to achieve at least k
occurrences of each character. If it is not possible to achieve this, we will return -1.
Solution:
Solutions
class Solution {
public int minMinutes(String s, int k) {
int[] count = new int[3]; // to store the count of 'a', 'b', 'c'
int total = 0; // total count of characters in the window
int left = 0, right = 0; // window pointers
int minMinutes = Integer.MAX_VALUE;
for (char ch : s.toCharArray()) {
count[ch - 'a']++;
total++;
while (count[0] >= k && count[1] >= k && count[2] >= k) {
minMinutes = Math.min(minMinutes, total);
count[s.charAt(left) - 'a']--;
total--;
left++;
}
}
return minMinutes == Integer.MAX_VALUE ? -1 : minMinutes;
}
}
Loading editor...