Maximum Number of Words Found in Sentences - Problem

Imagine you're analyzing a collection of sentences to find the most verbose one! ๐Ÿ“

A sentence is defined as a list of words separated by exactly one space with no leading or trailing spaces. You're given an array of strings called sentences, where each sentences[i] represents a single, well-formatted sentence.

Your task is to return the maximum number of words that appear in any single sentence from the array.

Example: If you have sentences like ["I love programming", "Code every day to improve", "Hello"], the answer would be 5 because "Code every day to improve" contains the most words.

Input & Output

example_1.py โ€” Basic Case
$ Input: ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
โ€บ Output: 6
๐Ÿ’ก Note: The first sentence has 5 words, second has 4 words, and third has 6 words. Maximum is 6.
example_2.py โ€” Single Word Sentences
$ Input: ["please wait", "continue to fight", "continue to win"]
โ€บ Output: 3
๐Ÿ’ก Note: The sentences have 2, 3, and 3 words respectively. Maximum is 3.
example_3.py โ€” Single Sentence
$ Input: ["hello world"]
โ€บ Output: 2
๐Ÿ’ก Note: Only one sentence with 2 words, so the maximum is 2.

Constraints

  • 1 โ‰ค sentences.length โ‰ค 100
  • 1 โ‰ค sentences[i].length โ‰ค 100
  • sentences[i] consists only of lowercase English letters and spaces
  • sentences[i] does not have leading or trailing spaces
  • All words in sentences[i] are separated by exactly one space

Visualization

Tap to expand
๐ŸŽฏ Word Counting Competition๐Ÿ‘จโ€โš–๏ธJudge๐Ÿ—ฃ๏ธSpeaker 15 words๐Ÿ—ฃ๏ธSpeaker 24 words๐Ÿ—ฃ๏ธSpeaker 36 wordsCounting...๐Ÿ† WINNERMost words:6
Understanding the Visualization
1
Judge listens to first speaker
Count words: 'alice and bob love leetcode' = 5 words
2
Judge listens to second speaker
Count words: 'i think so too' = 4 words (less than 5)
3
Judge listens to third speaker
Count words: 'this is great thanks very much' = 6 words (new max!)
4
Announce the winner
The most talkative speaker used 6 words
Key Takeaway
๐ŸŽฏ Key Insight: We only need to iterate through each sentence once and count its words, keeping track of the maximum count as we go!
Asked in
Amazon 15 Google 12 Microsoft 8 Meta 6
98.4K Views
Medium Frequency
~8 min Avg. Time
2.8K 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