Maximum Number of Integers to Choose From a Range I - 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].
  • Each integer can be chosen at most once.
  • The chosen integers should not be in the array banned.
  • The sum of the chosen integers should not exceed maxSum.

Return the maximum number of integers you can choose following the mentioned rules.

Input & Output

Example 1 — Basic Selection
$ Input: banned = [1,6,5], n = 5, maxSum = 6
Output: 2
💡 Note: Available numbers are [2,3,4]. We can pick 2 and 4 (sum=6≤6) for maximum count of 2.
Example 2 — No Banned Numbers
$ Input: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1
Output: 0
💡 Note: Only number 8 is available, but 8 > maxSum=1, so we can't pick any numbers.
Example 3 — Small Range
$ Input: banned = [11], n = 7, maxSum = 50
Output: 7
💡 Note: Numbers [1,2,3,4,5,6,7] are all available. Sum = 1+2+3+4+5+6+7 = 28 ≤ 50, so pick all 7.

Constraints

  • 1 ≤ banned.length ≤ 104
  • 1 ≤ banned[i], n ≤ 104
  • 1 ≤ maxSum ≤ 109

Visualization

Tap to expand
Maximum Integers from Range INPUT banned array: 1 6 5 Range [1, n=5]: 1 banned 2 OK 3 OK 4 OK 5 banned n = 5 maxSum = 6 banned = [1, 6, 5] Hash Set (banned): {1, 5, 6} ALGORITHM STEPS 1 Create Hash Set Store banned nums for O(1) lookup 2 Iterate 1 to n Check each number in order 3 Skip if Banned Use hash set to check 4 Add if sum allows Greedy: pick smallest first Execution Trace: i=1: banned, skip i=2: sum=2, count=1 i=3: sum=5, count=2 i=4: 5+4=9 > 6, stop i=5: banned, skip FINAL RESULT Chosen integers: 2 3 Sum: 2 + 3 = 5 5 <= maxSum(6) OK Output: 2 Maximum count of integers that can be chosen: 2 Adding 4 would exceed maxSum Key Insight: Greedy approach works because we want to maximize COUNT, not sum. By selecting smaller numbers first (from 1 to n), we leave more room in maxSum for additional numbers. Using a Hash Set for banned numbers gives O(1) lookup. Time: O(n), Space: O(banned.length) TutorialsPoint - Maximum Number of Integers to Choose From a Range I | Greedy Selection with Hash Set
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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