Skip to content

Commit 7395619

Browse files
Solve daily problem with easy code
1 parent af0d96e commit 7395619

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
Intuition
2+
Since we can use the same soldier for multiple teams, we just need to find number of ratings less than index i , mumber of ratings greater than index i which are on the left side of the index i and similarly umber of ratings less than index i , mumber of ratings greater than index i which are on the right side of the index i, multiply and add it to the answer.
3+
4+
Approach
5+
Iterate over the array.
6+
For every index i calculate the following:
7+
lowerThanLeft
8+
higherThanLeft
9+
lowerThanRight
10+
higherThanRight
11+
Multiply lowerThanLeft and higherThanRight, similarly multiply higherThanLeft and lowerThanRight and add it to answer.
12+
Complexity
13+
Time complexity:
14+
O(n^2)
15+
Space complexity:
16+
O(1)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution
2+
{
3+
public:
4+
int numTeams(vector<int> &rating)
5+
{
6+
const int m = rating.size();
7+
int ans = 0;
8+
for (int i = 1; i < m - 1; ++i)
9+
{
10+
int lowerThanLeft = 0;
11+
int higherThanLeft = 0;
12+
int lowerThanRight = 0;
13+
int higherThanRight = 0;
14+
for (int j = 0; j < i; ++j)
15+
{
16+
if (rating[j] < rating[i])
17+
{
18+
++lowerThanLeft;
19+
}
20+
else if (rating[j] > rating[i])
21+
{
22+
++higherThanLeft;
23+
}
24+
}
25+
for (int j = i + 1; j < m; ++j)
26+
{
27+
if (rating[j] < rating[i])
28+
{
29+
++lowerThanRight;
30+
}
31+
else if (rating[j] > rating[i])
32+
{
33+
++higherThanRight;
34+
}
35+
}
36+
ans += ((lowerThanLeft * higherThanRight) + (higherThanLeft * lowerThanRight));
37+
}
38+
return ans;
39+
}
40+
};

0 commit comments

Comments
 (0)