Count Number of Teams

`n` soldiers stand in a line, each with a unique `rating`. Choose 3 soldiers with indices `i < j < k` to form a team. A team is valid if `rating[i] < rating[j] < rating[k]` or `rating[i] > rating[j] > rating[k]`. Return how many valid teams can be formed. A soldier may be part of several teams.

30:00

Count Number of Teams
medium
Free written solution
Topics
Companies

n soldiers stand in a line, each with a unique rating. Choose 3 soldiers with indices i < j < k to form a team. A team is valid if rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k]. Return how many valid teams can be formed. A soldier may be part of several teams.

Example 1:
Input: {"rating":[2,5,3,4,1]}
Output: 3
Constraints:
  • n==rating.lengthn == \text{rating.length}

  • 3≤n≤10003 \leq n \leq 1000

  • 1≤rating[i]≤1051 \leq \text{rating}[i] \leq 10^5

  • All the integers in rating are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"rating":[2,5,3,4,1]}

2

5

3

4

1

■ middle j■ lower than middle■ higher than middle

lower left

·

higher left

·

lower right

·

higher right

·

rising = lowerLeft × higherRight, falling = higherLeft × lowerRight

teams = 0

teams added with each soldier as the middle

Every team has a middle soldier j. Fix j, count who is smaller or bigger on each side, and multiply: that counts all teams through j without listing them.

Variables
VariableValue
n5
teams0
DepthFunction Call
Stack empty
0/10