The problem states:
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 eachsentences[i]
represents a single sentence.Return the maximum number of words that appear in a single sentence.
Example:
Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] Output: 6 Explanation: - The first sentence, "alice and bob love leetcode", has 5 words in total. - The second sentence, "i think so too", has 4 words in total. - The third sentence, "this is great thanks very much", has 6 words in total. Thus, the maximum number of words in a single sentence comes from the third sentence, with a total of 6 words.
If I were in a real interview, I’d ask these clarifying questions. For now, I’ll assume:
sentences
could be of any length.Here’s how we can implement this strategy in Python:
def mostWordsFound(sentences):
max_count = 0
for sentence in sentences:
word_count = len(sentence.split())
if word_count > max_count:
max_count = word_count
return max_count
# Example usage:
sentences = [
"alice and bob love leetcode",
"i think so too",
"this is great thanks very much"
]
print(mostWordsFound(sentences)) # Output: 6
The time complexity of this solution is O(n), where n is the number of characters in the input list sentences
. This is because:
Overall, the solution is efficient for large inputs and should perform well within the typical problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?