The Wayback Machine - https://web.archive.org/web/20230225070729/https://www.geeksforgeeks.org/count-maximum-number-of-words-in-array/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Count maximum number of words in Array

Improve Article
Save Article
  • Last Updated : 24 Feb, 2023
Improve Article
Save Article

Given an array of strings arr[], where each arr[i] represents a single sentence with no leading or trailing spaces. Return the count of the maximum number of words that appear in a single string.

Input: arr[] = {“Welcome to geeks for geeks”, “Happy Coding”, “We love gfg”}
Output: 5
Explanation: The length of arr[0], arr[1] & arr[2] is 5, 2, 3. Among them, 5 is the maximum.

Input: arr[] = {“Start your coding journey”, “Ready to code”}
Output: 4

Approach: This can be solved by the following idea:

By iterating through the whole string and maintaining maximum words in each string.

Steps involved in the implementation of code: 

  • We have to iterate each string from arr.
  • Then find out the length of the strings & compare them with other strings.
  • After that compare the length with the other string’s length & return it.

Below is the implementation of the code:

Java




/* java program to find max length
of a word in arr */
  
import java.io.*;
  
class GFG {
  
    // Function that return the max length
    public static int countMaxLength(String arr[])
    {
  
        // Length of the array
        int n = arr.length;
  
        // Hold the max length
        int max = 0;
  
        for (int i = 0; i < n; i++) {
  
            // Creating a array of arr[i]
            // which is a string
            String sub[] = arr[i].split(" ");
            int len = sub.length;
  
            // Comparing the length
            max = Math.max(max, len);
        }
  
        // Return max words in string
        return max;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String arr[] = { "Welcome to geeks for geeks",
                         "Happy Coding", "We love gfg" };
  
        // Function call
        int ans = countMaxLength(arr);
        System.out.print(ans);
    }
}

Output

5

Time Complexity: O(n*len)
Auxiliary Space: O(len)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!