Maximum Number of Integers to Choose From a Range II - Problem
You are a mathematician working on a number selection puzzle! Given a range of integers from 1 to n, you need to strategically choose as many numbers as possible while following strict rules.
Your Mission:
- Choose integers from the range
[1, n] - Each integer can only be chosen once
- Avoid all numbers in the
bannedarray - Keep the total sum โค
maxSum
Goal: Return the maximum count of integers you can select while respecting all constraints.
Example: If n = 7, banned = [3, 5], and maxSum = 12, you could choose [1, 2, 4] (sum = 7) or [1, 2, 6] (sum = 9), but [1, 2, 4, 6] (sum = 13) exceeds maxSum. The optimal choice is [1, 2, 4, 6] if we can fit it within the sum limit!
Input & Output
example_1.py โ Basic Case
$
Input:
banned = [3, 5], n = 7, maxSum = 12
โบ
Output:
3
๐ก Note:
We can choose [1, 2, 4] with sum = 7. We cannot add 6 because 7 + 6 = 13 > 12. Number 7 would also exceed the limit.
example_2.py โ Large Numbers Banned
$
Input:
banned = [6, 7, 8], n = 10, maxSum = 15
โบ
Output:
5
๐ก Note:
We can choose [1, 2, 3, 4, 5] with sum = 15. This uses exactly maxSum and gives us the maximum possible count.
example_3.py โ Small maxSum
$
Input:
banned = [2, 4], n = 6, maxSum = 4
โบ
Output:
2
๐ก Note:
We can only choose [1, 3] with sum = 4. Adding 5 would make sum = 9 > 4, so we stop at count = 2.
Constraints
- 1 โค banned.length โค 104
- 1 โค banned[i], n โค 104
- 1 โค maxSum โค 109
- All elements in banned are unique
Visualization
Tap to expand
Understanding the Visualization
1
Identify Available Items
Create a list of items not in the banned list (out-of-stock items)
2
Start with Cheapest
Begin with item #1 (costs $1), then #2 (costs $2), etc.
3
Check Budget
For each item, verify that buying it won't exceed our maxSum budget
4
Stop When Needed
Once an item would exceed our budget, we've found our maximum count
Key Takeaway
๐ฏ Key Insight: The greedy approach works because smaller numbers leave more "budget room" for additional selections, naturally maximizing the total count we can achieve.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code