Untitled

 avatar
unknown
plain_text
a month ago
1.7 kB
2
Indexable
import java.util.HashMap;

class Solution {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        int result = k; // Initialize result to k
        HashMap<Character, Integer> mp = new HashMap<>(); // Frequency map

        int i = 0, j = 0; // Sliding window pointers
        while (j < answerKey.length()) {
            // Increment frequency of the current character
            char currentChar = answerKey.charAt(j);
            mp.put(currentChar, mp.getOrDefault(currentChar, 0) + 1);

            // If the minimum count of 'T' or 'F' exceeds k, shrink the window
            while (Math.min(mp.getOrDefault('T', 0), mp.getOrDefault('F', 0)) > k) {
                char startChar = answerKey.charAt(i);
                mp.put(startChar, mp.get(startChar) - 1);
                i++; // Move the start of the window forward
            }

            // Update the result with the current window size
            result = Math.max(result, j - i + 1);

            // Expand the window
            j++;
        }

        return result;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        String answerKey1 = "TTFF";
        int k1 = 2;
        System.out.println(solution.maxConsecutiveAnswers(answerKey1, k1)); // Output: 4

        String answerKey2 = "TFFT";
        int k2 = 1;
        System.out.println(solution.maxConsecutiveAnswers(answerKey2, k2)); // Output: 3

        String answerKey3 = "TTFTTFTT";
        int k3 = 1;
        System.out.println(solution.maxConsecutiveAnswers(answerKey3, k3)); // Output: 5
    }
}
Editor is loading...
Leave a Comment