Skip to content

Commit ea59925

Browse files
authored
Merge pull request #341 from Aaryan-Degama/main
day 2 solution 2
2 parents 3116c5b + 1c1726c commit ea59925

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

Problems/Mathematics/Day-02/sol/Aaryan_Degama/Solution1.cpp

Whitespace-only changes.
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Submission link: https://codeforces.com/contest/1475/submission/355643230
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
#define fastio ios::sync_with_stdio(false); cin.tie(NULL);
7+
8+
using ll = long long;
9+
const ll MOD = 1e9 + 7;
10+
11+
ll binexp(ll a, ll b) {
12+
ll res = 1;
13+
a %= MOD;
14+
while (b) {
15+
if (b & 1) res = res * a % MOD;
16+
a = a * a % MOD;
17+
b >>= 1;
18+
}
19+
return res;
20+
}
21+
22+
vector<ll> fac(1001);
23+
24+
ll nCr(ll n, ll r) {
25+
if (r < 0 || r > n) return 0;
26+
return fac[n] * binexp(fac[r], MOD - 2) % MOD * binexp(fac[n - r], MOD - 2) % MOD;
27+
}
28+
29+
void solve() {
30+
ll n, k;
31+
cin >> n >> k;
32+
vector<ll> v(n);
33+
for (ll &x : v) cin >> x;
34+
35+
sort(v.begin(), v.end());
36+
37+
ll ele = v[n - k];
38+
ll total = 0;
39+
40+
for (ll x : v) {
41+
if (x == ele) total++;
42+
}
43+
44+
ll taken = 0;
45+
for (ll i = n - k; i < n; i++) {
46+
if (v[i] == ele) taken++;
47+
}
48+
49+
cout << nCr(total, taken) << "\n";
50+
}
51+
52+
int main() {
53+
fastio
54+
55+
fac[0] = 1;
56+
for (int i = 1; i <= 1000; i++) {
57+
fac[i] = fac[i - 1] * i % MOD;
58+
}
59+
60+
int t;
61+
cin >> t;
62+
while (t--) solve();
63+
return 0;
64+
}
65+
66+
67+
/*
68+
Explaination :
69+
70+
To maximize the sum, we must always select the k largest elements of the array.
71+
Any selection that excludes one of the k largest elements will produce a smaller sum.
72+
If all elements were distinct, the answer would be 1, since the k largest elements
73+
are uniquely determined. However, when duplicate values exist, multiple selections
74+
can result in the same maximum sum.
75+
76+
Approach:
77+
1. Sort the array in non-decreasing order.
78+
2. The k largest elements are the last k elements of the sorted array.
79+
3. Let 'ele' be the smallest element among these k elements (i.e., ele = v[n - k]).
80+
4. Some elements larger than 'ele' are forced to be chosen, but occurrences of 'ele'
81+
introduce flexibility.
82+
83+
84+
Time Complexity : O(n log(n))
85+
Space Complexity : O(n)
86+
87+
*/

0 commit comments

Comments
 (0)