Skip to content

Commit 4db69af

Browse files
authored
Merge pull request #462 from Krishna200608/feature/issue-405-robin-hood
Solved Issue #405: Robin Hood in Town (Binary Search)
2 parents 6c477fb + 3fb9ca1 commit 4db69af

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+

0 commit comments

Comments
 (0)