Maximum Number of Groups Entering a Competition — LeetCode 2358 Python Solution

MediumGreedyArrayMathBinary Search
Problem
#2358
Reading time
2 min

The 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).

Example

Input
grades = [10,6,12,7,3,5]
Output
3
Explanation
The following is a possible way to form 3 groups of students:

Python solution

Python
class Solution:
    def maximumGroups(self, grades: List[int]) -> int:
        n = len(grades)
        return bisect_right(range(n + 1), n * 2, key=lambda x: x * x + x) - 1

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(1), where n is the total number of students auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2358. Maximum Number of Groups Entering a Competition is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2358. Maximum Number of Groups Entering a Competition?
LeetCode 2358. Maximum Number of Groups Entering a Competition is rated Medium on LeetCode.
What is the time complexity of LeetCode 2358. Maximum Number of Groups Entering a Competition?
The Python solution on this page runs in O(\log n).
What is the space complexity of LeetCode 2358. Maximum Number of Groups Entering a Competition?
The Python solution on this page uses O(1), where n is the total number of students auxiliary space.
What topics does LeetCode 2358. Maximum Number of Groups Entering a Competition cover?
LeetCode 2358. Maximum Number of Groups Entering a Competition is tagged Greedy, Array, Math and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview