# Count Number of Teams in C++

Suppose there are n soldiers standing in a line. Here each soldier is assigned a unique rating value. We have to make a team of 3 soldiers amongst them using the following rules −

Choose 3 soldiers with index (i, j, k) such that the rating (rating[i], rating[j], rating[k]).

A team will be valid if − (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]).

We have to find the number of teams we can form. (soldiers can be part of multiple teams).

So, if the input is like rating = [2,5,3,4,1], then the output will be 3, as we can form three teams like (2,3,4), (5,4,1), (5,3,1).

To solve this, we will follow these steps −

• ret := 0, n := size of v

• for initialize i := 0, when i < n, update (increase i by 1), do −

• for initialize j := i + 1, when j < n, update (increase j by 1), do −

• for initialize k := j + 1, when k < n, update (increase k by 1), do −

• if v[i] < v[j] and v[j] < v[k], then −

• (increase ret by 1)

• otherwise when v[i] > v[j] and v[j] > v[k], then −

• (increase ret by 1)

• return ret

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numTeams(vector<int>& v) {
int ret = 0;
int n = v.size();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if (v[i] < v[j] && v[j] < v[k])
ret++;
else if (v[i] > v[j] && v[j] > v[k])
ret++;
}
}
}
return ret;
}
};
main(){
Solution ob;
vector<int> v = {2,5,3,4,1};
cout << (ob.numTeams(v));
}

## Input

{2,5,3,4,1}

## Output

3