1 minute read

2024. Maximize the Confusion of an Exam (medium)

Failed at 24/66
문제를 잘못 이해했음;;

class Solution:
    def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
        i = 0
        n = len(answerKey)
        arr = []
        while i < n:
            cur = answerKey[i]
            j = i
            while j < n and answerKey[j] == cur:
                j += 1
            arr.append((cur, j - i))
            i = j
        
        res = 0
        m = len(arr)
        for index in range(m):
            prev = arr[index - 1][1] if index - 1 >= 0 else 0
            cur = arr[index][1]
            next_ = arr[index + 1][1] if index + 1 < m else 0
            if cur <= k:
                res = max(res, prev + next_ + cur)
            else:
                res = max(res, prev + k, next_ + k)
        
        return res

Another my solution

class Solution:
    def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
        n = len(answerKey)
        def help(target):
            counter = Counter()
            res = 0
            i = j = 0
            while i < n:
                c = answerKey[i]
                counter[c] += 1
                if counter[target] <= k:
                    res = max(res, counter['T'] + counter['F'])
                else:
                    while j < i and counter[target] > k:
                        counter[answerKey[j]] -= 1
                        j += 1
                i += 1
            return res

        return max(help('T'), help('F'))

Simple Solution

class Solution:
    def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
        res, l = 0, 0
        count = {"T": 0, "F": 0}

        for r in range(len(answerKey)):
            count[answerKey[r]] += 1
            if (r - l + 1) - max(count.values()) > k:
                count[answerKey[l]] -= 1
                l += 1
            res = max(res, r - l + 1)
        return res