Problem
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
ith
group is less than the sum of the grades of students in the(i + 1)th
group, for all groups (except the last). - The total number of students in the
ith
group is less than the total number of students in the(i + 1)th
group, for all groups (except the last).
Return the maximum number of groups that can be formed.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Using Iterative Formula
First, sort all the grades. Then, assign 1 student to the first group, 2 students to the second group, and so on. This ensures that the i-th
group is smaller in size and sum compared to the (i+1)-th
group.
To determine the maximum possible k
such that 1 + 2 + ... + k <= n
:
Proof:
When we sort the groups by size, the first group must have at least 1 student, the second group at least 2 students, and the k-th
group at least k
students.
This demonstrates the upper limit of k
, and I have provided a method to achieve this arrangement.
Code
|
|
Complexity
- ⏰ Time complexity:
O(sqrt(n))
- 🧺 Space complexity:
O(1)
Method 2 - Using Binary Search
To find the largest k
such that 1 + 2 + ... + k <= n
, solve the inequality k(k + 1) / 2 <= n
. We can use binary search to determine the maximum k
that satisfies k(k + 1) / 2 <= n
.
Code
|
|
Complexity
- ⏰ Time complexity:
O(log 1000)
- 🧺 Space complexity:
O(1)
Method 3 - Using Mathematical Formula
Given 1 + 2 + ... + k <= n
, we derive that k(k + 1) / 2 <= n
. This can be rewritten as (k + 0.5)^2 <= 2n + 0.25
. Taking the square root on both sides, we get k + 0.5 <= sqrt(2n + 0.25)
. Finally, solving for k
, we find k <= sqrt(2n + 0.25) - 0.5
.
|
|
Code
|
|
Complexity
- ⏰ Time complexity:
O(1)
- 🧺 Space complexity:
O(1)