Maximum Number of Groups Entering a Competition Problem
Description
LeetCode Problem 2358.
You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:
- The sum of the grades of students in the
i^thgroup is less than the sum of the grades of students in the(i + 1)^thgroup, for all groups (except the last). - The total number of students in the
i^thgroup is less than the total number of students in the(i + 1)^thgroup, for all groups (except the last).
Return the maximum number of groups that can be formed.
Example 1:
Input: grades = [10,6,12,7,3,5]
Output: 3
Explanation: The following is a possible way to form 3 groups of students:
- 1^st group has the students with grades = [12]. Sum of grades: 12. Student count: 1
- 2^nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2
- 3^rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3
It can be shown that it is not possible to form more than 3 groups.
Example 2:
Input: grades = [8,8]
Output: 1
Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.
Constraints:
1 <= grades.length <= 10^51 <= grades[i] <= 10^5
Solution
Approach: Greedy + Binary Search
Sort the grades ascending and form groups of sizes 1, 2, 3, ..., k. Then both the sizes and the sums strictly increase from group to group. If the last group is too small, merge its students into the previous group, which keeps the conditions true. Only the sizes matter, so the answer is the largest k with 1 + 2 + ... + k <= n, i.e. k * (k + 1) / 2 <= n.
Find k by binary search on [1, n]: take mid = (l + r + 1) / 2; if mid * (mid + 1) > 2 * n it is too large, so set r = mid - 1, otherwise set l = mid. Return l. A square-root formula gives the same value.
Complexity: O(log n) time and O(1) extra space.
class Solution:
def maximumGroups(self, grades: List[int]) -> int:
n = len(grades)
l, r = 1, n
while l < r:
mid = (l + r + 1) >> 1
if mid * mid + mid > n * 2:
r = mid - 1
else:
l = mid
return l