Maximum Number of Groups Entering a Competition - 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.

Input & Output

Example 1 — Basic Case
$ Input: grades = [10,6,12,7,3,5]
Output: 3
💡 Note: Sort to get [3,5,6,7,10,12]. Form groups: [3] (sum=3), [5,6] (sum=11), [7,10,12] (sum=29). Constraints satisfied: 3 < 11 < 29 (sums) and 1 < 2 < 3 (sizes).
Example 2 — Small Array
$ Input: grades = [8,8]
Output: 1
💡 Note: With only 2 students, we can only form 1 group containing both students. Cannot form 2 groups because that would require the second group to have more students than the first.
Example 3 — Edge Case
$ Input: grades = [1,2,3,4,5,6]
Output: 3
💡 Note: Already sorted. Optimal grouping: [1] (sum=1), [2,3] (sum=5), [4,5,6] (sum=15). Cannot form 4 groups because we'd need groups of sizes 1,2,3,4 but only have 6 students total.

Constraints

  • 1 ≤ grades.length ≤ 105
  • 1 ≤ grades[i] ≤ 106

Visualization

Tap to expand
Maximum Number of Groups - Greedy Approach INPUT grades array: 10 6 12 7 3 5 0 1 2 3 4 5 Sorted grades: 3 5 6 7 10 12 n = 6 students Total sum = 43 Group Requirements: Group i: size < Group i+1 size Group i: sum < Group i+1 sum ALGORITHM STEPS 1 Sort Array Enables greedy selection 2 Find Max Groups 1+2+3+...+k <= n 3 Calculate k k*(k+1)/2 <= n 4 Form Groups Sizes: 1, 2, 3... Calculation for n=6: k=1: 1*(2)/2 = 1 <= 6 OK k=2: 2*(3)/2 = 3 <= 6 OK k=3: 3*(4)/2 = 6 <= 6 OK k=4: 4*(5)/2 = 10 > 6 NO Max k = 3 groups FINAL RESULT Formed Groups: Group 1 3 Sum: 3 Size: 1 Group 2 5 6 11 Size: 2 Group 3 7 10 12 29 Size: 3 Verification: Sizes: 1 < 2 < 3 | Sums: 3 < 11 < 29 Output: 3 Key Insight: The greedy insight is that if we form k groups with increasing sizes 1, 2, 3, ..., k, we need exactly 1+2+...+k = k*(k+1)/2 students. The maximum k satisfying k*(k+1)/2 <= n gives the answer. TutorialsPoint - Maximum Number of Groups Entering a Competition | Greedy Approach
Asked in
Google 25 Amazon 20 Microsoft 15 Apple 12
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen