Maximum Number of Integers to Choose From a Range II — LeetCode 2557 Python Solution

MediumLeetCode PremiumGreedyArrayBinary SearchSorting
Problem
#2557
Reading time
3 min

The problem

You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules: The chosen integers have to be in the range [1, n].

Example

Input
banned = [1,4,6], n = 6, maxSum = 4
Output
1
Explanation
You can choose the integer 3.

Python solution

Python
class Solution:
    def maxCount(self, banned: List[int], n: int, maxSum: int) -> int:
        banned.extend([0, n + 1])
        ban = sorted(set(banned))
        ans = 0
        for i, j in pairwise(ban):
            left, right = 0, j - i - 1
            while left < right:
                mid = (left + right + 1) >> 1
                if (i + 1 + i + mid) * mid // 2 <= maxSum:
                    left = mid
                else:
                    right = mid - 1
            ans += left
            maxSum -= (i + 1 + i + left) * left // 2
            if maxSum <= 0:
                break
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 2557. Maximum Number of Integers to Choose From a Range II 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 2557. Maximum Number of Integers to Choose From a Range II?
LeetCode 2557. Maximum Number of Integers to Choose From a Range II is rated Medium on LeetCode.
What is the time complexity of LeetCode 2557. Maximum Number of Integers to Choose From a Range II?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2557. Maximum Number of Integers to Choose From a Range II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2557. Maximum Number of Integers to Choose From a Range II cover?
LeetCode 2557. Maximum Number of Integers to Choose From a Range II is tagged Greedy, Array, Binary Search and Sorting on LeetCode.
Is LeetCode 2557. Maximum Number of Integers to Choose From a Range II a premium problem?
Yes. LeetCode 2557. Maximum Number of Integers to Choose From a Range II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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