Maximum Number Of Vowels In A Substring

Introduction

 
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k. Note that vowel letters in English are [ a, e, i, o, u ]. So let's take an example where s is "abciiidef" and k is 3. so the output will be 3 because the substring "iii" contains 3 vowel letters in the string s. Given below are some more examples:
  1. static void Main(string[] args)  
  2. {  
  3.     var result = MaxVowels("abciiidef", 3);  
  4.     // example 1 : result = 3  
  5.     result = MaxVowels("aeiou", 2);  
  6.     // example 2 : result = 2  
  7.     result = MaxVowels("leetcode", 3);  
  8.     // example 3 : result = 2  
  9.     result = MaxVowels("rhythms", 4);  
  10.     // example 4 : result = 0  
  11.     result = MaxVowels("tryhard", 4);  
  12.     // example 5 : result = 1  
  13. }  

Solution

 
Our approach towards the problem will be simplest, we will have nested loops one which will substring the string s and the next will count the vowels in that substring. Here are the steps to how it's done,
  1. Create a list of vowels for reference and assign [ a, e, i, o, u ].
  2. Iterate from 0th to (s.Length - k)th index of the string s to get all the substrings of length k.
  3. Count the vowels for every substring.
  4. Compare every vowel count of substrings and return the maximum vowel count.
Here is the C# code for the algorithm given above:
  1. public static int MaxVowels(string s, int k)  
  2. {  
  3.     int maxVowels = 0;  
  4.     List<char> vowels = new List<char> { 'a''e''i''o''u' };  
  5.     for (int i = 0; i <= s.Length - k; i++)  
  6.     {  
  7.         string substring = s.Substring(i, k);  
  8.         int countVowels = substring.Where(x => vowels.Contains(x)).Count();  
  9.         maxVowels = Math.Max(countVowels, maxVowels);  
  10.     }  
  11.     return maxVowels;