Maximum count of Strings to be selected such that there is a majority character
Last Updated :
31 Aug, 2021
Given an array A[]of N strings of lowercase characters, the task is to find maximum number of strings, such that one character has majority i.e. the occurrence of one character in all of the strings is greater than all the other characters combined.
Examples:
Input: A[] = {"aba", "abcde", "aba"}
Output: 2
Explanation: On choosing {"aba", "aba"}, the occurrence of character 'a' is 4 and the occurrence of rest of the characters is 2, which is less than 4. So, a maximum of 2 strings can be chosen.
Input: A[] = {"bzc", "zzzdz", "e"}
Output: 3
Explanation: All the strings can be chosen, where 'z' has the majority.
Approach: There is a Greedy Solution to this problem. The idea is that, consider all the lowercase characters from 'a' to 'z' and for every character, find the maximum number of strings that can be chosen, so that the occurrence of that character is greater than all the other characters combined. Maximum of them will be the answer. Now the main problem is how to find the maximum number of strings such that one particular character has majority, to solve this use greedy algorithm. The idea is that, to find the maximum number of strings for a particular character 'ch', try to choose the strings in which occurrence of 'ch' is greatest compared to the occurrence of all the other characters, i.e. the strings in which (occurrence of 'ch' - occurrence of all other character) is maximum so that it will be possible to add more strings in the future.
Follow the steps below to solve the problem:
- Define a function CalDif(string s, char ch) and perform the following tasks:
- Initialize the variables chcount as 0 to store the count of that character and othercount as 0 to store the count of other characters.
- Traverse the string s using the variable x and perform the following tasks:
- If character at current position is ch, then increase the value of chcount by 1 else increase the value of othercount by 1.
- Return the difference between chcount and othercount.
- Initialize the variable ans and assign 0, it will store the final answer.
- Iterate over the lower-case character range [a, z] using the variable i and perform the following steps:
- Initialize a vector arr[] of length N, where arr[i] will store (occurrence of ch - occurrence of all other character) for i-th string.
- Run a loop from i=0 to N-1
- For the ith string compute (occurrence of ch - occurrence of all other character) using the function CalDiff(A[i], ch) and assign it to arr[i].
- Sort arr[] in decreasing order.
- Initialize two variables temp and count and assign 0 to them.
- Traverse the array arr[] and do temp += arr[i] and count++, where i starts from 0, until temp <= 0.
- Set the value of ans max of ans and count.
- After performing the above steps, print the value of ans as the answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate (occurrence of ch -
// occurrence of all other characters combined)
int CalDiff(string s, char ch)
{
// Initialize ch count as 0
int chcount = 0;
// Initialize all other char count as 0
int othercount = 0;
// Traversing the string
for (auto x : s) {
// Current character is ch
if (x == ch)
chcount++;
// Current character is not ch
else
othercount++;
}
// Return the final result
return (chcount - othercount);
}
// Function to calculate maximum number of string
// with one character as majority
int MaximumNumberOfString(string A[], int N)
{
// Initializing ans with 0, to store final answer
int ans = 0;
// For every character from 'a' to 'z' run loop
for (char ch = 'a'; ch <= 'z'; ch++) {
// Initialize arr to store character count
// difference
vector<int> arr(N);
// Traverse every string
for (int i = 0; i < N; i++) {
// Calculate the required value by
// function call and assign it to arr[i]
arr[i] = CalDiff(A[i], ch);
}
// Sort arr[] in decreasing order
sort(arr.begin(), arr.end(), greater<int>());
// Initialize temp and count as 0
int temp = 0, count = 0;
// Adding the first arr[] element to temp
temp += arr[0];
// Maintaining j as index
int j = 1;
// Run loop until temp <= 0
while (temp > 0) {
// Increasing count
count++;
// Adding temp with next arr[] element
if (j != N)
temp += arr[j++];
else
break;
}
// Set ans as max of ans and count
ans = max(ans, count);
}
// Returning the final result
return ans;
}
// Driver Code
int main()
{
// Input
string A[] = { "aba", "abcde", "aba" };
int N = sizeof(A) / sizeof(A[0]);
// Function call
cout << MaximumNumberOfString(A, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to calculate (occurrence of ch -
// occurrence of all other characters combined)
static int CalDiff(String s, char ch)
{
// Initialize ch count as 0
int chcount = 0;
// Initialize all other char count as 0
int othercount = 0;
// Traversing the String
for (int x : s.toCharArray())
{
// Current character is ch
if (x == ch)
chcount++;
// Current character is not ch
else
othercount++;
}
// Return the final result
return (chcount - othercount);
}
// Function to calculate maximum number of String
// with one character as majority
static int MaximumNumberOfString(String A[], int N)
{
// Initializing ans with 0, to store final answer
int ans = 0;
// For every character from 'a' to 'z' run loop
for (char ch = 'a'; ch <= 'z'; ch++) {
// Initialize arr to store character count
// difference
int []arr = new int[N];
// Traverse every String
for (int i = 0; i < N; i++) {
// Calculate the required value by
// function call and assign it to arr[i]
arr[i] = CalDiff(A[i], ch);
}
// Sort arr[] in decreasing order
Arrays.sort(arr);
arr = reverse(arr);
// Initialize temp and count as 0
int temp = 0, count = 0;
// Adding the first arr[] element to temp
temp += arr[0];
// Maintaining j as index
int j = 1;
// Run loop until temp <= 0
while (temp > 0)
{
// Increasing count
count++;
// Adding temp with next arr[] element
if (j != N)
temp += arr[j++];
else
break;
}
// Set ans as max of ans and count
ans = Math.max(ans, count);
}
// Returning the final result
return ans;
}
static int[] reverse(int a[]) {
int i, n = a.length, t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
// Driver Code
public static void main(String[] args)
{
// Input
String A[] = { "aba", "abcde", "aba" };
int N = A.length;
// Function call
System.out.print(MaximumNumberOfString(A, N));
}
}
// This code is contributed by Amit Katiyar
Python3
# Python 3 program for the above approach
# Function to calculate (occurrence of ch -
# occurrence of all other characters combined)
def CalDiff(s, ch):
# Initialize ch count as 0
chcount = 0
# Initialize all other char count as 0
othercount = 0
# Traversing the string
for x in s:
# Current character is ch
if (x == ch):
chcount += 1
# Current character is not ch
else:
othercount += 1
# Return the final result
return (chcount - othercount)
# Function to calculate maximum number of string
# with one character as majority
def MaximumNumberOfString(A, N):
# Initializing ans with 0, to store final answer
ans = 0
# For every character from 'a' to 'z' run loop
for ch in range(97,123,1):
# Initialize arr to store character count
# difference
arr = [0 for i in range(N)]
# Traverse every string
for i in range(N):
# Calculate the required value by
# function call and assign it to arr[i]
arr[i] = CalDiff(A[i], chr(ch))
# Sort arr[] in decreasing order
arr.sort(reverse = True)
# Initialize temp and count as 0
temp = 0
count = 0
# Adding the first arr[] element to temp
temp += arr[0]
# Maintaining j as index
j = 1
# Run loop until temp <= 0
while (temp > 0):
# Increasing count
count += 1
# Adding temp with next arr[] element
if (j != N):
temp += arr[j]
j += 1
else:
break
# Set ans as max of ans and count
ans = max(ans, count)
# Returning the final result
return ans
# Driver Code
if __name__ == '__main__':
# Input
A = ["aba", "abcde", "aba"]
N = len(A)
# Function call
print(MaximumNumberOfString(A, N))
# This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach
using System;
class GFG{
// Function to calculate (occurrence of ch -
// occurrence of all other characters combined)
static int CalDiff(string s, char ch)
{
// Initialize ch count as 0
int chcount = 0;
// Initialize all other char count as 0
int othercount = 0;
// Traversing the String
foreach(int x in s.ToCharArray())
{
// Current character is ch
if (x == ch)
chcount++;
// Current character is not ch
else
othercount++;
}
// Return the final result
return(chcount - othercount);
}
// Function to calculate maximum number of String
// with one character as majority
static int MaximumNumberOfString(string[] A, int N)
{
// Initializing ans with 0, to store final answer
int ans = 0;
// For every character from 'a' to 'z' run loop
for(char ch = 'a'; ch <= 'z'; ch++)
{
// Initialize arr to store character count
// difference
int []arr = new int[N];
// Traverse every String
for(int i = 0; i < N; i++)
{
// Calculate the required value by
// function call and assign it to arr[i]
arr[i] = CalDiff(A[i], ch);
}
// Sort arr[] in decreasing order
Array.Sort(arr);
arr = reverse(arr);
// Initialize temp and count as 0
int temp = 0, count = 0;
// Adding the first arr[] element to temp
temp += arr[0];
// Maintaining j as index
int j = 1;
// Run loop until temp <= 0
while (temp > 0)
{
// Increasing count
count++;
// Adding temp with next arr[] element
if (j != N)
temp += arr[j++];
else
break;
}
// Set ans as max of ans and count
ans = Math.Max(ans, count);
}
// Returning the final result
return ans;
}
static int[] reverse(int[] a)
{
int i, n = a.Length, t;
for(i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
// Driver Code
public static void Main(String []args)
{
// Input
string[] A = { "aba", "abcde", "aba" };
int N = A.Length;
// Function call
Console.WriteLine(MaximumNumberOfString(A, N));
}
}
// This code is contributed by sanjoy_62
JavaScript
<script>
// Javascript program for the above approach
// Function to calculate (occurrence of ch -
// occurrence of all other characters combined)
function CalDiff(s, ch) {
// Initialize ch count as 0
let chcount = 0;
// Initialize all other char count as 0
let othercount = 0;
// Traversing the string
for (let x of s) {
// Current character is ch
if (x == ch) chcount++;
// Current character is not ch
else othercount++;
}
// Return the final result
return chcount - othercount;
}
// Function to calculate maximum number of string
// with one character as majority
function MaximumNumberOfString(A, N) {
// Initializing ans with 0, to store final answer
let ans = 0;
// For every character from 'a' to 'z' run loop
for (let ch = "a".charCodeAt(0); ch <= "z".charCodeAt(0); ch++) {
// Initialize arr to store character count
// difference
let arr = new Array(N);
// Traverse every string
for (let i = 0; i < N; i++) {
// Calculate the required value by
// function call and assign it to arr[i]
arr[i] = CalDiff(A[i], String.fromCharCode(ch));
}
// Sort arr[] in decreasing order
arr.sort((a, b) => b - a);
// Initialize temp and count as 0
let temp = 0,
count = 0;
// Adding the first arr[] element to temp
temp += arr[0];
// Maintaining j as index
let j = 1;
// Run loop until temp <= 0
while (temp > 0) {
// Increasing count
count++;
// Adding temp with next arr[] element
if (j != N) temp += arr[j++];
else break;
}
// Set ans as max of ans and count
ans = Math.max(ans, count);
}
// Returning the final result
return ans;
}
// Driver Code
// Input
let A = ["aba", "abcde", "aba"];
let N = A.length;
// Function call
document.write(MaximumNumberOfString(A, N));
// This code is contributed by _saurabh_jaiswal.
</script>
Time Complexity: O(N * |s|), where |s| is maximum string length.
Auxiliary Space: O(N)
Similar Reads
Split a String into two Substring such that the sum of unique characters is maximum
Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible. Examples: Input: str = "abcabcdâ Output: 7Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 +
14 min read
Length of the smallest sub-string consisting of maximum distinct characters
Given a string of length N, find the length of the smallest sub-string consisting of maximum distinct characters. Note : Our output can have same character. Examples: Input : "AABBBCBB"Output : 5Input : "AABBBCBBAC"Output : 3Explanation : Sub-string -> "BAC"Input : "GEEKSGEEKSFOR"Output : 8Explan
15+ min read
Minimum K such that every substring of length atleast K contains a character c
Given a string S containing lowercase latin letters. A character c is called K-amazing if every substring of S with length atleast K contains this character c. Find the minimum possible K such that there exists atleast one K-amazing character. Examples: Input : S = "abcde" Output :3 Explanation : Ev
11 min read
Count of times second string can be formed from the characters of first string
Given two strings str and patt, the task is to find the count of times patt can be formed using the characters of str. Examples: Input: str = "geeksforgeeks", patt = "geeks" Output: 2 "geeks" can be made at most twice from the characters of "geeksforgeeks". Input: str = "abcbca", patt = "aabc" Outpu
6 min read
Count the maximum number of elements that can be selected from the array
Given an array arr[], the task is to count the maximum number of elements that can be selected from the given array following the below selection process: At 1st selection, select an element which is greater than or equal to 1.At 2nd selection, select an element which is greater than or equal to 2.A
5 min read
Maximize partitions such that no two substrings have any common character
Given string s of size n, the task is to print the number of substrings formed after maximum possible partitions such that no two substrings have a common character.Examples: Input : s = "ababcbacadefegdehijhklij" Output : 3 Explanation: Partitioning at the index 8 and at 15 produces three substring
1 min read
Count ways to partition a string such that both parts have equal distinct characters
Content has been removed on Author's request.
1 min read
Minimum K such that every substring of length at least K contains a character c | Set-2
Given a string S consisting of N lowercase English alphabets, and also given that a character C is called K-amazing, if every substring of length at least K contains this character C, the task is to find the minimum possible K such that there exists at least one K-amazing character. Examples: Input:
8 min read
Count of sub-strings that do not contain all the characters from the set {'a', 'b', 'c'} at the same time
Given a string str consisting only of the characters 'a', 'b' and 'c', find the number of sub-strings that do not contain all the three characters at the same time.Examples: Input: str = "abc" Output: 5 The possible substrings are "a", "b", "c", "ab" and "bc"Input: str = "babac" Output: 12 Approach:
8 min read
Remove k characters in a String such that ASCII sum is minimum
Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2
7 min read