Smallest subset with sum greater than all other elements
Pattern: Candy and assign cookies
To beat the rest with as few values as possible, take the largest values first. Sort descending and keep adding until the taken sum is strictly greater than what is left.
The problem
Return the size of the smallest subset whose sum is strictly greater than the sum of all the other values (the values
are positive). [3, 1, 7, 1] gives 1; [2, 1, 2] gives 2.
Think first
- Which values give the most sum per item taken?
- When can you stop?
- Does order among equal values matter?
Hints
Brute force, and why it fails
Try every subset: O(2ⁿ × n).
The key insight
For a fixed count, the largest values give the largest taken sum, so the greedy finds the smallest count that wins.
Dry run
| taken | 7 |
|---|---|
| rest | 5 |
arr = [3, 1, 7, 1]. Total 12. Largest first: 7.
Step 1 of 3
The plan
sort descending; taken = 0; rest = total
for x: if taken > rest: break; taken += x; rest -= x; count += 1
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates.
Edge cases
- One value: 1.
- All equal: just over half of them.
- One huge value: 1.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int minSubset(int[] arr) {
int[] a = arr.clone();
Arrays.sort(a);
long rest = 0, taken = 0;
for (int x : a) rest += x;
int count = 0;
for (int i = a.length - 1; i >= 0 && taken <= rest; i--) { // take the largest values first
taken += a[i];
rest -= a[i];
count++;
}
return count;
}
}C++
class Solution {
public:
int minSubset(vector<int>& arr) {
vector<int> a(arr);
sort(a.begin(), a.end());
long long rest = 0, taken = 0;
for (int x : a) rest += x;
int count = 0;
for (int i = static_cast<int>(a.size()) - 1; i >= 0 && taken <= rest; i--) { // take the largest values first
taken += a[i];
rest -= a[i];
count++;
}
return count;
}
};Python
class Solution:
def minSubset(self, arr: list[int]) -> int:
rest, taken, count = sum(arr), 0, 0
for x in sorted(arr, reverse=True): # take the largest values first
if taken > rest:
break
taken += x
rest -= x
count += 1
return countCommon mistakes
- Stopping at
taken >= rest; the problem needs strictly greater. - Sorting ascending.