There are
n
soldiers standing in a line. Each soldier is assigned a uniquerating
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).
O(n^3) solution is quite easy to think of. We need to compress the time complexity as the n is 1000 and n^2 is enough.
Now we can try to think in this way, if we could find how many numbers are smaller than the number at index j, we could also easily to find the number of teams fullfils the r[i] < r[j] < r[k].
let say if you find there are 3 numbers that smaller than r[j], if we are at r[k], and we find j < k and r[k] larger than r[j], we could just add 3 into our ans, because it fullfiled the requirements of team. Applying this logic into every cases, we can have the dp solution that is count all the number that smaller than and larger than specific index number, cost O(n^2).
class Solution {
public:
int numTeams(vector<int>& r) {
//dp[k] = dp[k - 1]+ (i < j < k) && ((r[i] < r[j] < r[k]) || (r[i] > r[j] > r[k]))
//where 3 <= k < n, 0 < j < k, 0 < i < j
int n = r.size();
int ans = 0;
vector<int> dp_f_j(n, 0);
vector<int> dp_b_j(n, 0);
for(int i = 1; i < n; i++){
for(int j = 0; j < i; j++){
if(r[i] > r[j]){
dp_f_j[i]++;
ans += dp_f_j[j];
}
if(r[i] < r[j]){
dp_b_j[i]++;
ans += dp_b_j[j];
}
}
}
return ans;
}
};