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 banned array
  • 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
๐Ÿ›’ Greedy Shopping StrategyBudget: $12 | Goal: Buy maximum itemsBudget Bar: Green (safe) โ†’ Yellow (caution) โ†’ Red (over)Available Items (prices = item numbers):$1โœ“ Buy$2โœ“ Buy$3Banned$4โœ“ Buy$5Banned$6Too muchRunning CalculationStep 1: Buy $1 item โ†’ Spent: $1, Items: 1Step 2: Buy $2 item โ†’ Spent: $3, Items: 2Step 3: Skip $3 (banned) โ†’ Still: $3, Items: 2Step 4: Buy $4 item โ†’ Spent: $7, Items: 3 โœ“ FINAL๐ŸŽฏ Key Insight: Smallest prices first = Maximum item count!
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.
Asked in
Google 42 Amazon 38 Meta 31 Microsoft 25
43.2K Views
Medium-High Frequency
~18 min Avg. Time
1.8K 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