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.
1def numTeams(rating):
2 count = 0
3 n = len(rating)
4 for i in range(n - 2):
5 for j in range(i + 1, n - 1):
6 for k in range(j + 1, n):
7 if (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]):
8 count += 1
9 return count
10
11ratings = [2, 5, 3, 4, 1]
12print(numTeams(ratings)) # Output: 3
This Python implementation uses three nested loops to generate all possible triplet indices and checks for valid team formations.
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)
1using System;
2
class Program {
public static int NumTeams(int[] rating) {
int count = 0;
int n = rating.Length;
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;
}
static void Main(string[] args) {
int[] ratings = {2, 5, 3, 4, 1};
Console.WriteLine(NumTeams(ratings)); // Output: 3
}
}
The C# code combines counting on both sides for each candidate middle soldier to find valid team counts.