Skip to content

Commit 12045ee

Browse files
committed
Add Python solution for Binary Search Day-06 q001
- Implemented solution for Codeforces 2014C (Robin Hood in Town) - Time complexity: O(n log n) - Space complexity: O(n) - Includes problem statement, approach, and complexity analysis
1 parent 143fed4 commit 12045ee

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

  • Problems/Binary-Search/Day-06/sol/Ishan_Raj_Singh
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Submission Link: https://codeforces.com/contest/2014/submission/356141020
3+
4+
Approach:
5+
1. If n <= 2, impossible to have more than half unhappy -> return -1
6+
2. Sort the wealth array
7+
3. Calculate current sum
8+
4. Find the median position (n//2)
9+
5. Use mathematical formula: For median person to be unhappy:
10+
(sum + X) / (2 * n) > a[median]
11+
Solving: X > 2 * n * a[median] - sum
12+
Therefore: X = 2 * n * a[median] - sum + 1
13+
14+
"""
15+
16+
def solve():
17+
n = int(input())
18+
a = list(map(int, input().split()))
19+
20+
if n <= 2:
21+
print(-1)
22+
return
23+
24+
a.sort()
25+
26+
total_sum = sum(a)
27+
28+
mid = n // 2
29+
30+
current_avg = total_sum / n
31+
unhappy_count = sum(1 for wealth in a if wealth < current_avg / 2)
32+
33+
if unhappy_count > n / 2:
34+
print(0)
35+
return
36+
37+
X = 2 * n * a[mid] - total_sum + 1
38+
39+
if X < 0:
40+
print(0)
41+
else:
42+
print(X)
43+
44+
t = int(input())
45+
for _ in range(t):
46+
solve()

0 commit comments

Comments
 (0)