Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximum count of Strings to be selected such that there is a majority character

  • Difficulty Level : Hard
  • 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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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>
Output
2

Time Complexity: O(N * |s|), where |s| is maximum string length.
Auxiliary Space: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!