LeetCode 2114. Maximum Number of Words Found in Sentences

LeetCode 2114. Maximum Number of Words Found in Sentences

Question : "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. " e.g .

" Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"].

Output: 6 "

  • The first thing we did is to initialize an integer variable to store our count.
  • Loop through the array of String of Sentence and split each of them by space.
  • After spliting Sentence[i] the result is stored in an array.
  • Count the array and if the result is greater than the value of the count variable set the count to the length of the array otherwise repreated the loop.
// Java
class Solution {
    public int mostWordsFound(String[] sentences) {
        int count = 0;   

        for(int i = 0; i<sentences.length;i++){  
            String[] f = sentences[i].trim().split("\\s+");
            if(f.length > count){
                count = f.length;
        return count;

Here is the Link to the Question on leetcode