Leetcode Daily Problem

Table of contents

No heading

No headings in the article.

1456. Maximum Number of Vowels in a Substring of Given Length

Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.

Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'

This question can be solved using the concept of the sliding window, we have to make a window of size of k, then we have to proceed.

  1. let's say we have i=0 and j=0 and we have k as the size of the window, j-i+1 at any point i,j gives the size of the window, mx to store max window size till now, a sum that will sum a number of vowels till this point.

  2. if(j-i+1<k) --> this means window size is not reached.

  3. if(j-i+1==k) --> means window size has reached.

  4. if the window size has not reached till now then J++

  5. if the window size is reached, find the sum of vowels in this window if it is greater than the previous then the new mx will be the sum.

  6. but before proceeding with i++ and j++ and moving to the very next window of size k, if nums[i] is a vowel then sum=sum-1.

int maxVowels(string s, int k) 
    {
        int n=s.length();

        // make a set that store all the vowels
        set<char>st;
        st.insert('a');
        st.insert('e');
        st.insert('i');
        st.insert('o');
        st.insert('u');

        int i=0;
        int j=0;

        int mx=INT_MIN;   // this will store max number of vowels till now
        int sum=0;        //cnt all the vowels till this point

        while(j<n)
        {
            // this if has condition that if s[j] is a vowel sum++
            if(st.find(s[j])!=st.end())
            {
                sum+=1;
            }

            // window of size k is not reached
            if((j-i+1)<k)
            {
                j++;
            }
            else
            // window of size k is reached
            if((j-i+1)==k)
            {
                mx=max(mx,sum);
                // if s[i] is vowel sum--
                if(st.find(s[i])!=st.end())
                {
                    sum=sum-1;
                }

                i++;
                j++;

            }
        }

        return mx;

    }