File tree Expand file tree Collapse file tree
Problems/Binary-Search/Day-06/sol/Krishna200608 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ Problem: Robin Hood in Town
3+ Link: https://codeforces.com/contest/2014/problem/C
4+ Author: Krishna200608
5+
6+ Short Problem Statement:=>
7+ Find minimum x to add to the richest person so that strictly more than half the population
8+ has wealth less than half the average.
9+
10+ Approach:
11+ If n <= 2, it's impossible (-1).
12+ Sort the array. The target person to become "poor" is at index n/2.
13+ Binary Search for x in range [0, 1e18].
14+ Condition: 2 * n * a[n/2] < current-sum + x.
15+
16+ Time : O(N log N)
17+ Space Complexity: O(1)
18+ */
19+
20+ /*
21+ Submission Link:
22+ https://codeforces.com/contest/2014/submission/356175570
23+ */
24+
25+ #include < bits/stdc++.h>
26+ using namespace std ;
27+ using ll = long long ;
28+ #define in (a ) for (int i = 0 ; i<a.size(); i++) cin>>a[i];
29+ typedef vector<int > vi;
30+ typedef vector<ll> vll;
31+
32+ void solve () {
33+ int n;
34+ cin >> n;
35+ vll a (n);
36+
37+ ll sum = 0 ;
38+ for (int i = 0 ; i < n; i++) {
39+ cin >> a[i];
40+ sum += a[i];
41+ }
42+
43+ if (n <= 2 ) {
44+ cout << " -1\n " ;
45+ return ;
46+ }
47+
48+ sort (a.begin (), a.end ());
49+
50+ ll l = 0 , r = 1e18 ;
51+ ll ans = -1 ;
52+
53+ while (l <= r) {
54+ ll mid = l + (r - l) / 2 ;
55+ if (2LL * n * a[n/2 ] < sum + mid) {
56+ ans = mid;
57+ r = mid - 1 ;
58+ } else {
59+ l = mid + 1 ;
60+ }
61+ }
62+ cout << ans << " \n " ;
63+ }
64+
65+ int main () {
66+ ios::sync_with_stdio (false );
67+ cin.tie (NULL );
68+ int t;
69+ cin >> t;
70+ while (t--) {
71+ solve ();
72+ }
73+ return 0 ;
74+ }
75+
You can’t perform that action at this time.
0 commit comments