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.
1using System;
2
3class Program {
4 public static int NumTeams(int[] rating) {
5 int count = 0;
6 int n = rating.Length;
7 for (int i = 0; i < n - 2; i++) {
8 for (int j = i + 1; j < n - 1; j++) {
9 for (int k = j + 1; k < n; k++) {
10 if ((rating[i] < rating[j] && rating[j] < rating[k]) ||
11 (rating[i] > rating[j] && rating[j] > rating[k])) {
12 count++;
13 }
14 }
15 }
16 }
17 return count;
18 }
19
20 static void Main(string[] args) {
21 int[] ratings = { 2, 5, 3, 4, 1 };
22 Console.WriteLine(NumTeams(ratings)); // Output: 3
23 }
24}
The C# solution also uses three nested loops to check all combinations of three soldiers to see if they meet the team criteria.
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)
1def
The Python solution efficiently calculates the number of valid teams by considering each potential middle soldier and counting appropriate soldiers on both sides.