LeetCode 2114: Maximum Number of Words Found in Sentences Solution

Master LeetCode problem 2114 (Maximum Number of Words Found in Sentences), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2114. Maximum Number of Words Found in Sentences

Problem Explanation

Explanation:

  • We need to find the maximum number of words in a single sentence from the given array of sentences.
  • We can achieve this by splitting each sentence into words using a space as a delimiter and counting the number of words in each sentence.
  • Finally, we return the maximum number of words found in any sentence.

Algorithm:

  1. Initialize a variable maxWords to store the maximum number of words found in a sentence.
  2. Iterate through each sentence in the input array.
  3. Split the current sentence into words using space as a delimiter.
  4. Count the number of words in the current sentence.
  5. Update maxWords if the number of words in the current sentence is greater than maxWords.
  6. Return maxWords as the result.

Time Complexity:
The time complexity of this algorithm is O(n*m), where n is the number of sentences and m is the average number of words in a sentence.

Space Complexity:
The space complexity is O(1) as we are not using any extra space that grows with the input size.

:

Solution Code

class Solution {
    public int maxWords(String[] sentences) {
        int maxWords = 0;
        for (String sentence : sentences) {
            String[] words = sentence.split(" ");
            maxWords = Math.max(maxWords, words.length);
        }
        return maxWords;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2114 (Maximum Number of Words Found in Sentences)?

This page provides optimized solutions for LeetCode problem 2114 (Maximum Number of Words Found in Sentences) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2114 (Maximum Number of Words Found in Sentences)?

The time complexity for LeetCode 2114 (Maximum Number of Words Found in Sentences) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2114 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2114 in Java, C++, or Python.

Back to LeetCode Solutions