File tree Expand file tree Collapse file tree
Problems/Mathematics/Day-02/sol/Sudhanshu Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ long long MOD = 1e9 + 7 ;
5+ long long fact[1005 ], invfact[1005 ];
6+
7+ long long modpow (long long a, long long b)
8+ {
9+ long long res = 1 ;
10+ while (b)
11+ {
12+ if (b & 1 )
13+ res = res * a % MOD;
14+ a = a * a % MOD;
15+ b >>= 1 ;
16+ }
17+ return res;
18+ }
19+
20+ long long nCr (int n, int r)
21+ {
22+ if (r < 0 || r > n)
23+ return 0 ;
24+ return fact[n] * invfact[r] % MOD * invfact[n - r] % MOD;
25+ }
26+
27+ int main ()
28+ {
29+ ios::sync_with_stdio (false );
30+ cin.tie (NULL );
31+
32+ fact[0 ] = 1 ;
33+ for (int i = 1 ; i <= 1000 ; i++)
34+ fact[i] = fact[i - 1 ] * i % MOD;
35+
36+ invfact[1000 ] = modpow (fact[1000 ], MOD - 2 );
37+ for (int i = 999 ; i >= 0 ; i--)
38+ invfact[i] = invfact[i + 1 ] * (i + 1 ) % MOD;
39+
40+ int t;
41+ cin >> t;
42+ while (t--)
43+ {
44+ int n, k;
45+ cin >> n >> k;
46+ vector<int > a (n);
47+ for (int i = 0 ; i < n; i++)
48+ cin >> a[i];
49+
50+ sort (a.begin (), a.end (), greater<int >());
51+
52+ int x = a[k - 1 ];
53+
54+ int total = 0 , need = 0 ;
55+ for (int i = 0 ; i < n; i++)
56+ if (a[i] == x)
57+ total++;
58+ for (int i = 0 ; i < k; i++)
59+ if (a[i] == x)
60+ need++;
61+
62+ cout << nCr (total, need) << " \n " ;
63+ }
64+ return 0 ;
65+ }
66+
67+ /*
68+ Approach
69+ - precompution factorials and inverse factorials
70+ - in the question it can be seen that max value can be only be attain my specific no. only after decreasing order
71+ - now it is possible there is a number which mai bi repeat multiple times so calculate the no. of ways using PnC using the precomputated factorials
72+
73+ - TC : O(nlogn) SC: O(n)
74+ */
You can’t perform that action at this time.
0 commit comments