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.
Example
Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"]
Output: 6
Explanation: The first sentence has 5 words, second sentence has 4 words, third sentence has 6 words, so the maximum number of words is 6.
My program:
int mostWordsFound(vector<string>& sentences) {
int n = sentences.size();
int max = 0;
for (int i = 0; i < n; i++) {
int counter = 0;
for (int j = 0; j < sentences[i].size(); j++) {
if (sentences[i][j] == ' ') counter++;
}
if (max < counter) max = counter;
}
return max + 1;
}
My program's output is correct, but the time complexity is O(n^2), are there any other ways to improve this program? Thanks.