Count Number of Teams — LeetCode 1395 Python Solution
MediumBinary Indexed TreeSegment TreeArrayDynamic Programming
- Problem
- #1395
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There are n soldiers standing in a line. Each soldier is assigned a unique rating value.
Example
- Input
- rating = [2,5,3,4,1]
- Output
- 3
- Explanation
- We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
Python solution
Python
class Solution:
def numTeams(self, rating: List[int]) -> int:
ans, n = 0, len(rating)
for i, b in enumerate(rating):
l = sum(a < b for a in rating[:i])
r = sum(c > b for c in rating[i + 1 :])
ans += l * r
ans += (i - l) * (n - i - 1 - r)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1395. Count Number of Teams is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1395. Count Number of Teams?
- LeetCode 1395. Count Number of Teams is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1395. Count Number of Teams?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 1395. Count Number of Teams?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1395. Count Number of Teams cover?
- LeetCode 1395. Count Number of Teams is tagged Binary Indexed Tree, Segment Tree, Array and Dynamic Programming on LeetCode.