Skip to content

2024. Maximize the Confusion of an Exam 👍

  • Time: $O(n)$
  • Space: $O(2) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int maxConsecutiveAnswers(string answerKey, int k) {
    int ans = 0;
    int maxCount = 0;
    vector<int> count(2);

    for (int l = 0, r = 0; r < answerKey.length(); ++r) {
      maxCount = max(maxCount, ++count[answerKey[r] == 'T']);
      while (maxCount + k < r - l + 1)
        --count[answerKey[l++] == 'T'];
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int maxConsecutiveAnswers(String answerKey, int k) {
    int ans = 0;
    int maxCount = 0;
    int[] count = new int[2];

    for (int l = 0, r = 0; r < answerKey.length(); ++r) {
      maxCount = Math.max(maxCount, ++count[answerKey.charAt(r) == 'T' ? 1 : 0]);
      while (maxCount + k < r - l + 1)
        --count[answerKey.charAt(l++) == 'T' ? 1 : 0];
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
    ans = 0
    maxCount = 0
    count = collections.Counter()

    l = 0
    for r, c in enumerate(answerKey):
      count[c == 'T'] += 1
      maxCount = max(maxCount, count[c == 'T'])
      while maxCount + k < r - l + 1:
        count[answerKey[l] == 'T'] -= 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans