Maximum Number of Words Found in Sentences - Problem

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.

You are given an array of strings sentences, where each sentences[i] represents a single sentence.

Return the maximum number of words that appear in a single sentence.

Input & Output

Example 1 — Basic Case
$ Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
💡 Note: First sentence has 5 words, second has 4 words, third has 6 words. Maximum is 6.
Example 2 — Single Word Sentences
$ Input: sentences = ["please wait", "continue to fight", "continue"]
Output: 3
💡 Note: Word counts are [2, 3, 1]. Maximum is 3 words in "continue to fight".
Example 3 — All Same Length
$ Input: sentences = ["w", "x", "y", "z"]
Output: 1
💡 Note: All sentences have exactly 1 word each. Maximum is 1.

Constraints

  • 1 ≤ sentences.length ≤ 100
  • 1 ≤ sentences[i].length ≤ 100
  • sentences[i] consists only of lowercase English letters and ' ' only
  • sentences[i] does not have leading or trailing spaces
  • All the words in sentences[i] are separated by a single space

Visualization

Tap to expand
Maximum Number of Words Found in Sentences INPUT sentences[] array [0] "alice and bob love leetcode" [1] "i think so too" [2] "this is great thanks very much" Word counts after split: 5 words 4 words 6 words 3 sentences total ALGORITHM STEPS 1 Initialize maxWords = 0 Track maximum count 2 Loop each sentence Iterate through array 3 Split by space Count = split.length 4 Update maximum maxWords = max(count) Split Example (sentence[2]): this is great thanks very much = 6 words (maximum!) FINAL RESULT Maximum words found: 6 Output: 6 Word Count Summary: sentences[0]: 5 words sentences[1]: 4 words sentences[2]: 6 words max(5, 4, 6) = 6 [OK] Solution Verified Key Insight: The number of words in a sentence = number of spaces + 1. Using split(" ") separates words by spaces, and the resulting array length gives the word count. Time Complexity: O(n * m) where n = sentences, m = avg length. TutorialsPoint - Maximum Number of Words Found in Sentences | String Split Method
Asked in
LeetCode 15 Microsoft 8
15.6K Views
Low Frequency
~5 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen