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'}
        l, r = 0, 0
        N = len(s)
        res = 0
        curr = 0
        for r in range(N):
            if s[r] in vowels:
                curr += 1
            if r - l + 1 >= k:
                res = max(res, curr)
                if s[l] in vowels:
                    curr -= 1
                l += 1

        return res

Editorial

Approach: Sliding Window

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