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 Integers from Range II INPUT Range [1, n] where n = 7 1 2 3 4 5 6 7 Available Banned Input Values banned = [2, 6] n = 7 maxSum = 15 Sum of chosen nums must be <= 15 GREEDY ALGORITHM 1 Sort Available Remove banned: [1,3,4,5,7] 2 Start Smallest Pick from 1 (greedy) 3 Add While Valid sum + num <= maxSum 4 Count Chosen Return count Selection Process: Pick 1: sum=1 [OK] Pick 3: sum=4 [OK] Pick 4: sum=8 [OK] Pick 5: sum=13 [OK] Skip 7: sum=20 >15 FINAL RESULT Chosen Integers: 1 3 4 5 1 + 3 + 4 + 5 = 13 13 <= 15 (maxSum) OUTPUT 4 Maximum count of integers chosen: 4 VERIFIED OK Key Insight: Greedy approach works optimally here: always pick the smallest available number first. This maximizes the count since smaller numbers leave more room in maxSum for additional numbers. TutorialsPoint - Maximum Number of Integers to Choose From a Range II | Greedy Approach
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