Leetcode 2114. Maximum Number of Words Found in Sentences
You are given a list of sentences, where each sentence is a string. Your task is to return the maximum number of words found in any single sentence.
Before we proceed, here are some questions to clarify the problem:
Assuming typical constraints and definitions:
Below is a Java implementation to solve the given problem:
public class Solution {
public int mostWordsFound(String[] sentences) {
int maxWords = 0;
for (String sentence : sentences) {
// Split each sentence by spaces to get words
String[] words = sentence.split(" ");
// Update the maximum words count
maxWords = Math.max(maxWords, words.length);
}
return maxWords;
}
public static void main(String[] args) {
Solution sol = new Solution();
String[] sentences = {
"alice and bob love leetcode",
"i think so too",
"this is great thanks very much"
};
System.out.println(sol.mostWordsFound(sentences)); // Output: 6
}
}
maxWords
to keep track of the maximum number of words found in a sentence." "
) as the delimiter.maxWords
if the number of words in the current sentence is greater than the previously recorded maximum.maxWords
..split(" ")
method is proportional to the number of words in a sentence, which would be managed by Java’s internal optimizations.This solution efficiently calculates the maximum number of words in any sentence using straightforward string manipulation techniques.
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?