Skip to content

Commit 54b7a7e

Browse files
code(java) : Solved que 1 of day-6
1 parent d0fba44 commit 54b7a7e

1 file changed

Lines changed: 90 additions & 0 deletions

File tree

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// -------------------- Problem --------------------
2+
/*
3+
There are n people in a town and each person has some gold.
4+
5+
The richest person suddenly finds extra gold (x coins) and adds it
6+
to their own wealth.
7+
8+
A person is called unhappy if their wealth becomes strictly less than
9+
half of the average wealth of all people.
10+
11+
If more than half of the people are unhappy, Robin Hood shows up.
12+
13+
For every test case, we need to find the minimum value of x that
14+
makes this happen. If it can never happen, print -1.
15+
*/
16+
17+
// -------------------- How this works --------------------
18+
/*
19+
Adding gold only increases the average, so the richest person will
20+
never be unhappy.
21+
22+
The only way Robin Hood appears is when more than half of the people
23+
fall below half of the average wealth.
24+
25+
So after sorting, we only care about the point where more than half
26+
of the population crosses this limit.
27+
28+
That point is the person at index n/2 (0-based). If this person
29+
becomes unhappy, then strictly more than half are unhappy.
30+
31+
From the inequality, we directly compute how much gold is needed.
32+
If the value comes out negative, zero is enough.
33+
34+
For n = 1 or 2, it is impossible to make more than half unhappy.
35+
*/
36+
37+
// -------------------- Complexity --------------------
38+
/*
39+
Sorting dominates the solution.
40+
Time: O(n log n)
41+
Space: O(n)
42+
*/
43+
44+
// -------------------- Submission --------------------
45+
/*
46+
https://codeforces.com/contest/2014/submission/355974166
47+
*/
48+
49+
// -------------------- Code -------------------------
50+
51+
import java.io.*;
52+
import java.util.*;
53+
54+
public class Solution1 {
55+
public static void main(String[] args) throws Exception {
56+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
57+
StringBuilder sb = new StringBuilder();
58+
59+
int t = Integer.parseInt(br.readLine());
60+
61+
while (t-- > 0) {
62+
int n = Integer.parseInt(br.readLine());
63+
StringTokenizer st = new StringTokenizer(br.readLine());
64+
65+
long[] a = new long[n];
66+
long sum = 0;
67+
68+
for (int i = 0; i < n; i++) {
69+
a[i] = Long.parseLong(st.nextToken());
70+
sum += a[i];
71+
}
72+
73+
if (n <= 2) {
74+
sb.append("-1\n");
75+
continue;
76+
}
77+
78+
Arrays.sort(a);
79+
80+
int idx = n / 2;
81+
long x = 2L * n * a[idx] - sum + 1;
82+
83+
if (x < 0) x = 0;
84+
85+
sb.append(x).append('\n');
86+
}
87+
88+
System.out.print(sb.toString());
89+
}
90+
}

0 commit comments

Comments
 (0)