# 1395. Count Number of Teams     • Time: $O(n^2)$
• Space: $O(1)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public: int numTeams(vector& rating) { int ans = 0; for (int i = 1; i < rating.size() - 1; ++i) { // Calculate soldiers on the left with less/greater ratings. int leftLess = 0; int leftGreater = 0; for (int j = 0; j < i; ++j) if (rating[j] < rating[i]) ++leftLess; else if (rating[j] > rating[i]) ++leftGreater; // Calculate soldiers on the right with less/greater ratings. int rightLess = 0; int rightGreater = 0; for (int j = i + 1; j < rating.size(); ++j) if (rating[j] < rating[i]) ++rightLess; else if (rating[j] > rating[i]) ++rightGreater; ans += leftLess * rightGreater + leftGreater * rightLess; } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Solution { public int numTeams(int[] rating) { int ans = 0; for (int i = 1; i < rating.length - 1; ++i) { // Calculate soldiers on the left with less/greater ratings. int leftLess = 0; int leftGreater = 0; for (int j = 0; j < i; ++j) if (rating[j] < rating[i]) ++leftLess; else if (rating[j] > rating[i]) ++leftGreater; // Calculate soldiers on the right with less/greater ratings. int rightLess = 0; int rightGreater = 0; for (int j = i + 1; j < rating.length; ++j) if (rating[j] < rating[i]) ++rightLess; else if (rating[j] > rating[i]) ++rightGreater; ans += leftLess * rightGreater + leftGreater * rightLess; } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution: def numTeams(self, rating: List[int]) -> int: ans = 0 for i in range(1, len(rating) - 1): # Calculate soldiers on the left with less//greater ratings. leftLess = 0 leftGreater = 0 for j in range(i): if rating[j] < rating[i]: leftLess += 1 elif rating[j] > rating[i]: leftGreater += 1 # Calculate soldiers on the right with less//greater ratings. rightLess = 0 rightGreater = 0 for j in range(i + 1, len(rating)): if rating[j] < rating[i]: rightLess += 1 elif rating[j] > rating[i]: rightGreater += 1 ans += leftLess * rightGreater + leftGreater * rightLess return ans