Count Number of Teams - Problem
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
You have to form a team of 3 soldiers amongst them under the following rules:
- Choose 3 soldiers with index
(i, j, k)with rating(rating[i], rating[j], rating[k]). - A team is valid if:
(rating[i] < rating[j] < rating[k])or(rating[i] > rating[j] > rating[k])where(0 <= i < j < k < n).
Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
Input & Output
Example 1 — Basic Case
$
Input:
rating = [2,5,3,4,1]
›
Output:
3
💡 Note:
We can form teams: [2,3,4] (ascending), [5,4,1] (descending), [5,3,1] (descending). Total = 3 teams.
Example 2 — Minimum Size
$
Input:
rating = [2,1,3]
›
Output:
0
💡 Note:
No valid teams can be formed. [2,1,3] is neither ascending (2>1) nor descending (1<3).
Example 3 — All Ascending
$
Input:
rating = [1,2,3,4,5]
›
Output:
10
💡 Note:
All possible triplets form ascending teams: (1,2,3), (1,2,4), (1,2,5), (1,3,4), (1,3,5), (1,4,5), (2,3,4), (2,3,5), (2,4,5), (3,4,5).
Constraints
- 3 ≤ rating.length ≤ 1000
- 1 ≤ rating[i] ≤ 105
- All the integers in rating are unique.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of soldier ratings: [2,5,3,4,1]
2
Find Teams
Look for ascending (i<j<k) or descending (i>j>k) patterns
3
Output
Count of valid 3-soldier teams: 3
Key Takeaway
🎯 Key Insight: Fix the middle soldier and multiply the count of valid left partners with valid right partners
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code