Maximum Number of Integers to Choose From a Range I - Problem

You're planning to select as many integers as possible from the range [1, n] while following strict rules. Think of it as a strategic number-picking game where you want to maximize your selections while staying within constraints.

The Rules:

  • ๐Ÿ“ Pick only from integers 1 to n
  • ๐Ÿšซ Avoid any numbers in the banned array
  • ๐Ÿ“Š Each number can only be chosen once
  • ๐Ÿ’ฐ The total sum must not exceed maxSum

Your goal is to return the maximum count of integers you can select following these rules.

Example: If n = 7, banned = [3, 6], and maxSum = 12, you could pick [1, 2, 4, 5] for a sum of 12 and count of 4.

Input & Output

example_1.py โ€” Python
$ Input: banned = [3, 6], n = 7, maxSum = 12
โ€บ Output: 4
๐Ÿ’ก Note: We can select [1, 2, 4, 5] with sum = 12. Numbers 3 and 6 are banned, and adding 7 would exceed maxSum.
example_2.py โ€” Python
$ Input: banned = [1, 6, 7], n = 7, maxSum = 5
โ€บ Output: 2
๐Ÿ’ก Note: We can select [2, 3] with sum = 5. Number 1 is banned, and adding 4 would make sum = 9 > 5.
example_3.py โ€” Python
$ Input: banned = [1, 2, 3, 4, 5, 6, 7], n = 7, maxSum = 10
โ€บ Output: 0
๐Ÿ’ก Note: All numbers from 1 to 7 are banned, so we cannot select any numbers.

Constraints

  • 1 โ‰ค banned.length โ‰ค 104
  • 1 โ‰ค banned[i], n โ‰ค 104
  • 1 โ‰ค maxSum โ‰ค 1015
  • All elements in banned are unique

Visualization

Tap to expand
Shopping Budget OptimizationStore Inventory (Price = Number)$1โœ“ BUY$2โœ“ BUY$3โœ— BANNED$4โœ“ BUY$5โœ“ BUY$6โœ— BANNED$7โœ— TOO EXPENSIVEShopping Cart & Budget TrackerBudget: $12Cart: [Item $1, Item $2, Item $4, Item $5]Total Spent: $12 (1+2+4+5)Items Purchased: 4MAX4Why Greedy Works:๐ŸŽฏ Key Insight: To maximize count, always choose smallest available numbers first๐Ÿ’ก Choosing 1+2+3 (count=3) is better than choosing 6 (count=1) with same budgetโšก Stop early when next item exceeds budget - larger items definitely won't fit
Understanding the Visualization
1
Mark Unavailable Items
Create a quick-lookup list of banned/out-of-stock items
2
Shop Smart
Start with cheapest items (1, 2, 3...) to maximize quantity
3
Budget Check
For each item, verify it fits within remaining budget
4
Early Exit
Stop when next item would exceed budget (no point checking expensive items)
Key Takeaway
๐ŸŽฏ Key Insight: Greedy selection of smallest valid numbers maximizes count while staying within budget constraints
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 19
28.7K Views
Medium Frequency
~15 min Avg. Time
892 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