2024. Maximize the Confusion of an Exam - Medium

前往題目

思路

1004題的進階

  1. sliding window
  2. 重複兩遍循環,一次是把T當作基準,也就是翻轉成T,一次是把F當作基準

Code

class Solution {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        int res = 0;
        int i = 0;
        int count = 0;

        // If flip to T
        for (int j = 0; j < answerKey.length(); ++j) {
            if (answerKey.charAt(j) == 'T') {
                res = Math.max(res, j - i + 1);
            } else {
                ++count;
                while (count > k) {
                    if (answerKey.charAt(i) == 'F') {
                        --count;
                    }
                    ++i;
                }
                res = Math.max(res, j - i + 1);
            }
        }

        i = 0;
        count = 0;

        // If flip to F
        for (int j = 0; j < answerKey.length(); ++j) {
            if (answerKey.charAt(j) == 'F') {
                res = Math.max(res, j - i + 1);
            } else {
                ++count;
                while (count > k) {
                    if (answerKey.charAt(i) == 'T') {
                        --count;
                    }
                    ++i;
                }
                res = Math.max(res, j - i + 1);
            }
        }

        return res;
    }
}

2024. Maximize the Confusion of an Exam - Medium
https://f88083.github.io/2024/02/01/2024-Maximize-the-Confusion-of-an-Exam-Medium/
作者
Simon Lai
發布於
2024年2月1日
許可協議