1395. Count Number of Teams(dp)

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 (ijk) 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;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值