Maximum Number of Words Found in Sentences
Problem
You are given an array of sentences, where each sentence is a string of words separated by single spaces with no leading or trailing spaces. Return the largest number of words that any single sentence in the array contains.
sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]6def most_words_found(sentences):
best = 0
for s in sentences:
words = s.count(' ') + 1
if words > best:
best = words
return best
function mostWordsFound(sentences) {
let best = 0;
for (const s of sentences) {
let words = 1;
for (const c of s) if (c === ' ') words++;
if (words > best) best = words;
}
return best;
}
class Solution {
public int mostWordsFound(String[] sentences) {
int best = 0;
for (String s : sentences) {
int words = 1;
for (char c : s.toCharArray()) if (c == ' ') words++;
if (words > best) best = words;
}
return best;
}
}
int mostWordsFound(vector<string>& sentences) {
int best = 0;
for (const string& s : sentences) {
int words = 1;
for (char c : s) if (c == ' ') words++;
if (words > best) best = words;
}
return best;
}
Explanation
The key observation is that the words in every sentence are separated by exactly one space, and there are no spaces at the start or end. That makes counting words almost free.
If a sentence has k spaces, those spaces sit between words, so they split the sentence into k + 1 pieces. In other words, word count = number of spaces + 1. We never even need to actually split the string.
So we walk through the list of sentences one at a time. For each sentence we count its spaces, add one, and compare that against the best (largest) count we have seen so far, keeping whichever is bigger.
Example: ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]. The first sentence has 4 spaces → 5 words. The second has 3 spaces → 4 words. The third has 5 spaces → 6 words. The running maximum ends at 6.
Because we only scan each character once and keep a single running maximum, the work is proportional to the total text length and uses just a couple of integer variables.