This is a straightforward fixed-size sliding window problem. We maintain a count of vowels in the current window of size k.
- Vowels set:
{'a', 'e', 'i', 'o', 'u'}. - Calculate vowels in the first
kcharacters. res = count.- Slide the window:
- If incoming char is vowel,
count += 1. - If outgoing char is vowel,
count -= 1. res = max(res, count).
- If incoming char is vowel,
- Return
res.
- Time Complexity: O(N).
- Space Complexity: O(1).
def max_vowels(s, k):
vowels = {'a', 'e', 'i', 'o', 'u'}
count = 0
for i in range(k):
if s[i] in vowels:
count += 1
res = count
for i in range(k, len(s)):
if s[i] in vowels:
count += 1
if s[i - k] in vowels:
count -= 1
res = max(res, count)
return res