---
# System prepended metadata

title: 2024. Maximize the Confusion of an Exam
tags: [Leetcode, Sliding Window, Medium]

---

# 2024. Maximize the Confusion of an Exam
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/maximize-the-confusion-of-an-exam/
## 思路
### 思路一 $O(N)$ $O(1)$
两次sliding window，一次替换F，一次替换T
### 思路二 $O(N)$ $O(1)$
参考[0424. Longest Repeating Character Replacement](https://hackmd.io/2OqRR7LlQq2TK0NEfLqhHw)
## Code
### 思路一
```java=
class Solution {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        return Math.max(count(answerKey, k, 'T'), count(answerKey, k, 'F'));
    }
    private int count(String answerKey, int k, char ch){
        int maxLen = 0;
        int count = 0;
        int l = 0, r = 0;
        while(r < answerKey.length()){
            if(answerKey.charAt(r)==ch) count++;
            if(count > k){
                while(l<r && count>k){
                    if(answerKey.charAt(l++)==ch){
                        count--;
                    }
                }
            }
            maxLen = Math.max(maxLen, r-l+1);
            r++;
        }
        return maxLen;
    }
}
```
### 思路二
```java=
class Solution {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        int[] count = new int[2];
        int l = 0, r = 0;
        int maxCnt = 0;
        int maxLen = 0;
        while(r<answerKey.length()){
            maxCnt = Math.max(maxCnt, ++count[answerKey.charAt(r)=='T'?0:1]);
            if(r-l+1-maxCnt>k){
                count[answerKey.charAt(l++)=='T'?0:1]--;
            }
            maxLen = Math.max(maxLen, r-l+1);
            r++;
        }
        return maxLen;
    }
}
```