Maximum Number of Integers to Choose From a Range II - 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 Case
$ Input: banned = [2,6], n = 7, maxSum = 15
Output: 4
💡 Note: We can choose [1,3,4,5]. These are not banned and sum to 13 ≤ 15. Cannot add 7 as 13+7=20 > 15.
Example 2 — Small Budget
$ Input: banned = [1,3], n = 4, maxSum = 4
Output: 1
💡 Note: Available numbers are [2,4]. We can only pick 2 (sum=2 ≤ 4). Adding 4 would make sum=6 > 4.
Example 3 — All Numbers Available
$ Input: banned = [], n = 3, maxSum = 6
Output: 3
💡 Note: No numbers are banned. We can pick [1,2,3] with sum=6 ≤ 6, selecting all 3 numbers.

Constraints

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

Visualization

Tap to expand
Maximum Integer Selection: banned=[2,6], n=7, maxSum=15Range [1, 7]:1234567✓ pick✗ banned✓ pick✓ pick✓ pick✗ banned✗ exceeds sumSelected: [1, 3, 4, 5]Sum: 1 + 3 + 4 + 5 = 13 ≤ 15 ✓Count: 4Why stop at 7?Current sum: 13Adding 7: 13 + 7 = 2020 > 15 (maxSum) ✗Maximum integers selected: 4
Understanding the Visualization
1
Input Analysis
Range [1,n], banned numbers, and sum limit maxSum
2
Greedy Selection
Pick smallest available numbers first to maximize count
3
Result
Maximum count of integers that satisfy all constraints
Key Takeaway
🎯 Key Insight: Greedy approach works because smaller numbers allow more selections within the sum limit
Asked in
Microsoft 12 Amazon 8 Google 5
8.5K Views
Medium Frequency
~15 min Avg. Time
234 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