Maximum Words in Sentence
Given an array of strings where each string represents a sentence containing words separated by single spaces, find the maximum number of words in any single sentence. Return the highest word count among all sentences.
For example, the sentences ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] have word counts 5, 4, and 6 respectively. The maximum is 6. An empty array returns 0.
Counting words in sentences is a fundamental text processing task. Word counts are used in readability analysis (Flesch-Kincaid grade level), document similarity (TF-IDF), text summarization, and search relevance scoring. The word count of a sentence is typically computed by counting the spaces plus one, or by splitting on spaces and taking the array length.
The simplest approach iterates through each sentence, splits it by spaces into words, counts them, and tracks the maximum count seen so far. This runs in O(N) time where N is the total number of characters across all sentences.
Edge cases include an empty array (return 0), a single empty string (return 0), sentences with one word (word count is 1), and all sentences having the same word count (return that count).
Example Input & Output
4 words in the sentence
2 words
Single word
Two words with extra spaces
Empty string
Algorithm Flow
Solution Approach
Iterate through sentences, count words in each, and track the maximum.
Initialize max to 0. For each sentence, split by spaces to get an array of words, take its length to get the word count. If the current count exceeds max, update max. After processing all sentences, return max.
An alternative approach counts spaces instead of splitting: the number of words equals the number of spaces plus one (for non-empty strings). This avoids creating intermediate arrays.
Time complexity is O(N) where N is total characters. Space complexity is O(1) aside from the split arrays.
Best Answers
class Solution {
public int solution(String s) {
s=s.trim();if(s.isEmpty())return 0;return s.split("\\s+").length;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
