You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We have a population of n people with given wealths. We want to give x gold to one person
8
-
(the richest) such that strictly more than half of the population becomes "unhappy".
9
-
A person is unhappy if their wealth is strictly less than half of the average wealth.
10
-
Find the minimum non-negative integer x to achieve this. If impossible, output -1.
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.
11
9
12
10
Approach:
13
-
We need to find the minimum integer x such that the count of people with wealth < (new_average / 2) is > n / 2.
14
-
1. If n <= 2, it is impossible to have strictly more than half the population satisfy the condition (since the max wealth will always be >= average). Output -1.
15
-
2. Sort the wealth array to easily count or check conditions.
16
-
3. The condition is monotonic: adding more gold increases the average, making it easier for existing wealths to fall below half the average.
17
-
4. We can Binary Search for x in the range [0, 1e18].
18
-
- Calculation: New Sum = Current Sum + mid.
19
-
- Check: We need strictly more than n/2 people to be poor.
20
-
In a sorted array, this means the person at index n/2 (0-indexed) must be poor.
21
-
Condition: a[n/2] < (Sum + mid) / (2 * n)
22
-
To avoid floating point errors, we use cross-multiplication:
23
-
2 * n * a[n/2] < Sum + mid
24
-
5. The smallest valid 'mid' is our answer.
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.
25
15
26
-
Time Complexity: O(n log n) due to sorting. Binary search takes O(log(1e18)) steps, each check is O(1).
0 commit comments