# Maximum distinct lowercase alphabets between two uppercase in C++

Given the task is to find the maximum number of distinct lower case alphabets that are present between two upper case alphabets in the given string.

Let’s now understand what we have to do using an example −

## Input

str = “JKyubDoorG”

## Output

3

## Explanation

“yub” is present between the two upper case alphabets K and D which makes the count 3.

“oor” is also present between the two upper case alphabets D and G which makes the count 2 as ‘o’ is a repeating alphabet and we are looking for distinct alphabets.

Therefore, the output is 3.

## Input

str = “ABcefsTaRpaep”

## Output

4

## Approach used in the below program as follows

• In function Max() initialize int size = s.length() to store the length of the given string.

• Loop from i = 0 till i<size and check if if (s[i] >= 'A' && s[i] <= 'Z'). If so then increment I and break;

• Initialize int ans = 0 to store the final answer and another array cnt[26] = {0}.

• Loop from i = 0 till i<size then check if (s[i] >= 'A' && s[i] <= 'Z') to check if the current alphabet is in upper case. If so then initialize int CurrMax = 0 to store the current maximum value.

• Loop from i = 0 till i<26 and check if (cnt[i] > 0). If so, then increment CurrMax.

• Outside the for loop, update ans by putting ans = max(ans, CurrMax); and reset the cnt[] array by using memset(cnt, 0, sizeof(cnt));

• Close the above if() statement and check if (s[i] >= 'a' && s[i] <= 'z'). If so then increment cnt[s[i] - 'a'].

• Close the for loop and return ans.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int Max(string s){
int size = s.length();
// Ignore the lowercase alphabets in beginning
for (int i = 0; i < size; i++){
if (s[i] >= 'A' && s[i] <= 'Z'){
i++;
break;
}
}
int ans = 0;
int cnt[26] = { 0 };
for (int i = 0; i < size; i++) {
// If alphabet is uppercase,
if (s[i] >= 'A' && s[i] <= 'Z'){
//Counting all lower case
//distinct alphabets
int CurrMax = 0;
for (int i = 0; i < 26; i++){
if (cnt[i] > 0)
CurrMax++;
}
// Update ans
ans = max(ans, CurrMax);
// Reset count array
memset(cnt, 0, sizeof(cnt));
}
// If alphabet is lowercase
if (s[i] >= 'a' && s[i] <= 'z')
cnt[s[i] - 'a']++;
}
return ans;
}
// Driver function
int main(){
string str = "JKyubDoorG";
cout << Max(str);
return 0;
}

## Output

3

Updated on: 04-Aug-2020

216 Views