1456. Maximum Number of Vowels in a Substring of Given Length
Problem
Return the maximum number of vowels in any substring of s of length exactly k.
Example: s = "abciiidef", k = 3 → 3 ("iii")
Fixed window of size k: add the entering character, subtract the leaving one, track the maximum.
Complexity: O(n).
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = set("aeiou")
cur = best = sum(c in vowels for c in s[:k])
for i in range(k, len(s)):
cur += (s[i] in vowels) - (s[i - k] in vowels)
best = max(best, cur)
return best
assert Solution().maxVowels("abciiidef", 3) == 3
assert Solution().maxVowels("aeiou", 2) == 2
assert Solution().maxVowels("leetcode", 3) == 2
assert Solution().maxVowels("tryhard", 4) == 1
class Solution {
public int maxVowels(String s, int k) {
int cur = 0, best = 0;
for (int i = 0; i < s.length(); i++) {
if ("aeiou".indexOf(s.charAt(i)) >= 0) cur++;
if (i >= k && "aeiou".indexOf(s.charAt(i - k)) >= 0) cur--;
best = Math.max(best, cur);
}
return best;
}
}
func maxVowels(s string, k int) int {
vowel := func(c byte) int {
if strings.IndexByte("aeiou", c) >= 0 {
return 1
}
return 0
}
cur := 0
for i := 0; i < k; i++ {
cur += vowel(s[i])
}
best := cur
for i := k; i < len(s); i++ {
cur += vowel(s[i]) - vowel(s[i-k])
best = max(best, cur)
}
return best
}