-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1395_Count_Number_of_Teams.cpp
More file actions
84 lines (70 loc) · 2.11 KB
/
1395_Count_Number_of_Teams.cpp
File metadata and controls
84 lines (70 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution {
public:
int numTeams(vector<int>& rating) {
int n=rating.size();
int k= count(rating); // for > > case
reverse(rating.begin(),rating.end());
k+=(count(rating)); // for < < case
return k;
}
int count(vector<int>& rating){
int n=rating.size();
vector<int> greater(n); //greater [i] store count of elements greater than rating[i] on right side
vector<int> smaller(n); // smaller [i] stores count of elements smaller than rating[i] on left side
for(int i=0;i<n;i++){
int target=rating[i];
int c=0;
for(int j=i+1;j<n;j++){
if(rating[j]>target)
c++;
}
greater[i]=c;
}
for(int i=0;i<n;i++){
int target=rating[i];
int c=0;
for(int j=i-1;j>=0;j--){
if(rating[j]<target)
c++;
}
smaller[i]=c;
}
int sum=0;
for(int i=0;i<n;i++)
sum+=(greater[i]*smaller[i]); //Total triplets with A[i] as middle element in ( <A[i] < ) this case
return sum;
}
};
Brute Force
class Solution {
public:
int numTeams(vector<int>& s) {
int n=s.size();
if(n<3)
return 0;
int sum=0;
for(int i=0;i<n-2;i++)
{
for(int j=i+1;j<n-1;++j)
{
for(int k=j+1;k<n;++k)
{
if(s[k]>s[j] && s[j]>s[i])
sum+=1;
}
}
}
for(int i=n-1;i>=2;--i)
{
for(int j=i-1;j>=1;--j)
{
for(int k=j-1;k>=0;--k)
{
if(s[k]>s[j] && s[j]>s[i])
sum+=1;
}
}
}
return sum;
}
};