less than 1 minute read

Problem Statement

leetcode problem link

My Solution [Accepted]

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = {'a','e','i','o','u'}
        start = 0
        N = len(s)
        res = 0
        length = 0
        count = 0
        for end in range(N):
            ch = s[end]
            while end - start + 1 > k:
                if s[start] in vowels:
                    count -= 1
                start += 1

            if ch in vowels:
                count += 1

            if end - start + 1 == k:
                res = max(res, count)

        return res

Editorial Solution

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = {'a', 'e', 'i', 'o', 'u'}

        # Build the window of size k, count the number of vowels it contains.
        count = 0
        for i in range(k):
            count += int(s[i] in vowels)
        answer = count

        # Slide the window to the right, focus on the added character and the
        # removed character and update "count". Record the largest "count".
        for i in range(k, len(s)):
            count += int(s[i] in vowels)
            count -= int(s[i - k] in vowels)
            answer = max(answer, count)

        return answer