Sponsored
Sponsored
This approach involves checking all possible combinations of three soldiers using nested loops to see if they can form a valid team. Although simple, this approach can be optimized by ensuring we scoot to the inner loops only when conditions are satisfied.
Time Complexity: O(n^3), where n is the length of the input array 'ratings'. This results from three nested loops each iterating over up to n elements.
Space Complexity: O(1), as it uses a constant amount of additional space.
1#include <stdio.h>
2
3int numTeams(int* rating, int ratingSize) {
4 int count = 0;
5 for (int i = 0; i < ratingSize - 2; i++) {
6 for (int j = i + 1; j < ratingSize - 1; j++) {
7 for (int k = j + 1; k < ratingSize; k++) {
8 if ((rating[i] < rating[j] && rating[j] < rating[k]) ||
9 (rating[i] > rating[j] && rating[j] > rating[k])) {
10 count++;
11 }
12 }
13 }
14 }
15 return count;
16}
17
18int main() {
19 int ratings[] = {2, 5, 3, 4, 1};
20 int size = sizeof(ratings) / sizeof(ratings[0]);
21 printf("%d\n", numTeams(ratings, size)); // Output: 3
22 return 0;
23}
The brute force solution uses three nested loops to iterate over all possible triplets of indices (i, j, k) and checks if they form a valid team according to the given conditions.
This approach reduces the number of nested loops from three to two by counting the number of elements to the left and right that satisfy the increasing or decreasing condition required for forming a team.
Time Complexity: O(n^2)
Space Complexity: O(1)
1#include <iostream>
2#include <vector>
using namespace std;
int numTeams(vector<int>& rating) {
int count = 0;
int n = rating.size();
for (int j = 0; j < n; j++) {
int less_left = 0, greater_left = 0, less_right = 0, greater_right = 0;
for (int i = 0; i < j; i++) {
if (rating[i] < rating[j]) less_left++;
else if (rating[i] > rating[j]) greater_left++;
}
for (int k = j + 1; k < n; k++) {
if (rating[j] < rating[k]) less_right++;
else if (rating[j] > rating[k]) greater_right++;
}
count += less_left * less_right + greater_left * greater_right;
}
return count;
}
int main() {
vector<int> ratings = {2, 5, 3, 4, 1};
cout << numTeams(ratings) << endl; // Output: 3
return 0;
}
This C++ solution follows the same optimized strategy as the C solution, by reducing the problem complexity with judicious counting.